
import { useRef, useState } from "react";
import { StepValidationStatus, TripMember, TripStep } from "@/types";
import { Card } from "@/components/ui/card";
import { StepComments } from "../StepComments";
import { useTrips } from "@/contexts/TripContext";
import { toast } from "sonner";
import { EditStepDialog } from "./edit/EditStepDialog";
import { getStepTypeById } from "@/types/stepTypes";
import { StepDetailDialog } from "./details/StepDetailDialog";
import { StepCardContent } from "./card/StepCardContent";
import { StepCardFooter } from "./card/StepCardFooter";
import { Badge } from "@/components/ui/badge";
import { ChevronRight, FileText, MapPin, MessageSquare } from "lucide-react";
import { countTravelerStepDecisions, getTravelerStepDecisions } from "@/services/stepValidationSummary";
import { StepImage } from "./StepImage";

interface TripStepCardProps {
  step: TripStep;
  tripId: string;
  isPlanner: boolean;
  dayDate?: string | null;
  members?: TripMember[];
  documentsCount?: number;
  onSelectStep?: (step: TripStep, dayDate?: string | null) => void;
  selected?: boolean;
}

export function TripStepCard({ step, tripId, isPlanner, dayDate, members, documentsCount = 0, onSelectStep, selected = false }: TripStepCardProps) {
  const [showComments, setShowComments] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showDetailsDialog, setShowDetailsDialog] = useState(false);
  const [pendingStatus, setPendingStatus] = useState<'validating' | 'rejecting' | 'publishing' | 'unpublishing' | null>(null);
  const deletingRef = useRef(false);
  const mutationRef = useRef(false);
  const { deleteTripStep, validateTripStep, publishTripStep } = useTrips();

  // Assure-toi que step.stepType existe, sinon utilise 'activity' comme fallback
  const stepType = step.stepType || 'activity';

  // Get step type info and colors
  const stepTypeInfo = getStepTypeById(stepType);
  const { light: bgColor, accent: accentColor } = stepTypeInfo.colors;

  const handleDeleteStep = async () => {
    if (deletingRef.current) return;
    const confirmDelete = window.confirm("Êtes-vous sûr de vouloir supprimer cette étape ?");
    if (confirmDelete) {
      deletingRef.current = true;
      try {
        const success = await deleteTripStep(tripId, step.id);
        if (!success) throw new Error("Suppression non confirmée");
        toast.success("Étape supprimée avec succès !");
      } catch (error) {
        console.error("Erreur lors de la suppression de l'étape", error);
        toast.error("Erreur lors de la suppression de l'étape.");
      } finally {
        deletingRef.current = false;
      }
    }
  };

  const handleValidateStep = async (status: Exclude<StepValidationStatus, "pending">) => {
    if (mutationRef.current) return;
    mutationRef.current = true;
    setPendingStatus(status === 'approved' ? 'validating' : 'rejecting');

    try {
      const success = await validateTripStep(tripId, step.id, status);
      if (!success) throw new Error("Validation non confirmée");
      toast.success(status === 'approved' ? "Étape approuvée !" : "Étape refusée !");
    } catch (error) {
      console.error("Erreur lors de la décision sur l'étape", error);
      toast.error("La décision n'a pas pu être enregistrée.");
    } finally {
      setPendingStatus(null);
      mutationRef.current = false;
    }
  };

  // Fonction pour gérer la publication des étapes
  const handlePublishStep = async (isPublished: boolean) => {
    if (mutationRef.current) return;
    mutationRef.current = true;
    setPendingStatus(isPublished ? 'publishing' : 'unpublishing');

    try {
      const success = await publishTripStep(tripId, step.id, isPublished);
      if (!success) throw new Error("Publication non confirmée");
      toast.success(isPublished ? "Étape publiée avec succès !" : "Étape masquée avec succès !");
    } catch (error) {
      console.error("Erreur lors de la modification de la visibilité", error);
      toast.error("La visibilité de l'étape n'a pas pu être modifiée.");
    } finally {
      setPendingStatus(null);
      mutationRef.current = false;
    }
  };

  // Event handlers
  const handleOpenComments = () => setShowComments(true);
  const handleOpenEditDialog = () => setShowEditDialog(true);
  const handleOpenDetailsDialog = () => onSelectStep ? onSelectStep(step, dayDate) : setShowDetailsDialog(true);

  // Formater la date si dayDate est disponible
  const formattedDate = dayDate || "";

  if (isPlanner && onSelectStep) {
    const counts = countTravelerStepDecisions(getTravelerStepDecisions(step.validations, members));
    return <div className="relative">
      <div className="absolute -left-10 top-6 h-5 w-5 rounded-full border-4 border-white" style={{ backgroundColor: accentColor }} />
      <button type="button" aria-pressed={selected} onClick={() => onSelectStep(step, dayDate)} className={`group grid w-full grid-cols-[3.25rem_minmax(0,1fr)] items-start gap-x-3 gap-y-3 rounded-lg border-l-2 px-2 py-4 text-left transition hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary sm:grid-cols-[70px_minmax(0,1fr)_auto] sm:items-center sm:gap-4 sm:px-3 ${selected ? "border-l-primary bg-muted/50" : "border-l-transparent bg-transparent"}`}>
        <span className="pt-1 font-semibold text-secondary sm:pt-0">{step.startTime || step.time || "—"}</span>
        <span className="col-start-2 flex min-w-0 flex-col gap-3 sm:row-start-1 sm:flex-row sm:items-center">
          {step.imagePath && <StepImage step={step} variant="planner-thumbnail" />}
          <span className="min-w-0"><span className="text-xs font-medium text-muted-foreground">{stepTypeInfo.label}{step.estimatedDuration ? ` · ${step.estimatedDuration}` : ""}</span><span className="mt-0.5 block font-semibold text-secondary sm:truncate">{step.activity}</span>{step.location && <span className="mt-1 flex items-center gap-1 text-sm text-muted-foreground sm:truncate"><MapPin className="h-3.5 w-3.5 shrink-0" />{step.location}</span>}<span className="mt-2 flex flex-wrap gap-2"><Badge variant={step.isPublished ? "default" : "outline"}>{step.isPublished ? "Visible voyageur" : "Masquée aux voyageurs"}</Badge>{counts.approved > 0 && <Badge className="status-success">{counts.approved} validé</Badge>}{counts.rejected > 0 && <Badge variant="destructive">{counts.rejected} modification demandée</Badge>}{counts.pending > 0 && <Badge variant="secondary">{counts.pending} à valider</Badge>}</span></span>
        </span>
        <span className="col-start-2 flex items-center gap-3 text-sm text-muted-foreground sm:col-start-3 sm:row-start-1"><span className="flex items-center gap-1" aria-label={`${documentsCount} document(s)`}><FileText className="h-4 w-4" />{documentsCount}</span><span className="flex items-center gap-1" aria-label={`${step.comments.length} commentaire(s)`}><MessageSquare className="h-4 w-4" />{step.comments.length}</span><ChevronRight className="ml-auto h-5 w-5 transition group-hover:translate-x-0.5 sm:ml-0" /></span>
      </button>
    </div>;
  }

  return (
    <>
      <div className="relative">
        <div
          className="absolute -left-10 top-5 rounded-full w-5 h-5"
          style={{
            backgroundColor: accentColor,
            borderColor: 'white',
            borderWidth: '4px'
          }}
        />
        <Card
          className="cursor-pointer overflow-visible bg-white shadow-none transition-all duration-200 hover:border-primary/35 hover:shadow-[0_10px_28px_rgba(20,33,61,0.08)]"
          style={{
            backgroundColor: 'white',
            borderColor: '#E7E3DC',
            borderWidth: '1px',
            opacity: (isPlanner && !step.isPublished) ? 0.7 : 1
          }}
          onClick={handleOpenDetailsDialog}
        >
          <StepCardContent
            step={step}
            pendingStatus={pendingStatus}
            dayDate={formattedDate}
            stepTypeIcon={stepTypeInfo.icon}
            isPlanner={isPlanner}
            members={members}
          />

          <StepCardFooter
            isPlanner={isPlanner}
            commentsCount={step.comments?.length || 0}
            accentColor={accentColor}
            bgColor={bgColor}
            onOpenComments={handleOpenComments}
            onOpenEdit={handleOpenEditDialog}
            onDelete={handleDeleteStep}
            onValidate={handleValidateStep}
            onPublish={handlePublishStep}
            validationStatus={step.validationStatus}
            isPublished={step.isPublished}
            pendingStatus={pendingStatus}
            stepType={stepType}
            tripId={tripId}
            stepId={step.id}
          />
        </Card>
      </div>

      {/* Step details dialog */}
      {!onSelectStep && <StepDetailDialog
        step={step}
        isPlanner={isPlanner}
        isOpen={showDetailsDialog}
        onClose={() => setShowDetailsDialog(false)}
        onEdit={() => {
          setShowDetailsDialog(false);
          setTimeout(() => setShowEditDialog(true), 100);
        }}
        onPublish={handlePublishStep}
        pendingStatus={pendingStatus}
        dayDate={formattedDate}
        members={members}
      />}

      {/* Comments dialog */}
      {showComments && (
        <StepComments
          isOpen={showComments}
          onClose={() => setShowComments(false)}
          tripId={tripId}
          step={step}
        />
      )}

      {/* Edit step dialog */}
      {showEditDialog && (
        <EditStepDialog
          isOpen={showEditDialog}
          onClose={() => setShowEditDialog(false)}
          step={step}
          tripId={tripId}
        />
      )}
    </>
  );
}
