
import { TripStep } from "../../types";
import { useTrips } from "../../contexts/TripContext";
import { useState, useEffect, useRef } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { formatDateTime } from "@/lib/utils";
import { useSupabaseComments } from "../../hooks/useSupabaseComments";
import { useIsMobile } from "@/hooks/use-mobile";
import { Loader2 } from "lucide-react";
import { COMMENT_MAX_LENGTH, normalizeCommentContent } from "@/services/commentGuards";

interface StepCommentsProps {
  isOpen: boolean;
  onClose: () => void;
  tripId: string;
  step: TripStep;
  initialMessage?: string;
}

export function StepComments({ isOpen, onClose, tripId, step, initialMessage = "" }: StepCommentsProps) {
  const { addStepComment } = useTrips();
  const { getStepComments } = useSupabaseComments();
  const isMobile = useIsMobile();
  const [newComment, setNewComment] = useState(initialMessage);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [sendFeedback, setSendFeedback] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [comments, setComments] = useState(step.comments || []);
  const commentsLoadedRef = useRef(false);
  const submittingRef = useRef(false);

  // Charger les commentaires frais une seule fois lors de l'ouverture du dialogue
  useEffect(() => {
    if (isOpen && step.id && !commentsLoadedRef.current) {
      console.group("📝 Chargement des commentaires frais dans StepComments");
      console.log("Étape ID:", step.id);

      const fetchComments = async () => {
        commentsLoadedRef.current = true;
        setIsLoading(true);
        setLoadError(null);
        try {
          const freshComments = await getStepComments(step.id);
          setComments(freshComments);
        } catch (error) {
          console.error("Erreur lors du chargement des commentaires", error);
          setLoadError("Les commentaires n'ont pas pu être chargés.");
        } finally {
          setIsLoading(false);
        }
      };

      fetchComments();
      console.groupEnd();
    }

    // Réinitialiser le flag lorsque le dialogue se ferme
    if (!isOpen) {
      commentsLoadedRef.current = false;
    }
  }, [isOpen, step.id, getStepComments]);

  // Mise à jour des commentaires lorsque les props changent (nouveau commentaire ajouté)
  useEffect(() => {
    if (step.comments && step.comments.length > 0) {
      setComments(prevComments => {
        // Ne mettre à jour que si nous avons plus de commentaires ou si nous n'en avons pas encore récupéré
        if (step.comments.length > prevComments.length || prevComments.length === 0) {
          return step.comments;
        }
        return prevComments;
      });
    }
  }, [step.comments]);

  const handleAddComment = async () => {
    if (submittingRef.current) return;
    let content: string;
    try {
      content = normalizeCommentContent(newComment);
    } catch (error) {
      setSendFeedback({ type: "error", text: error instanceof Error ? error.message : "Commentaire invalide." });
      return;
    }
    submittingRef.current = true;
    setIsSubmitting(true);
      try {
        const addedComment = await addStepComment(tripId, step.id, { content });
        if (!addedComment) throw new Error("Insertion non confirmée");

        setComments(prev => (prev.some(comment => comment.id === addedComment.id)
          ? prev
          : [...prev, addedComment]
        ).sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)));
        setNewComment("");
        setSendFeedback({ type: "success", text: "Message envoyé" });
      } catch (error) {
        console.error('Erreur lors de l\'ajout du commentaire:', error);
        setSendFeedback({ type: "error", text: "Le message n’a pas pu être envoyé. Votre texte est conservé, vous pouvez réessayer." });
      } finally {
        setIsSubmitting(false);
        submittingRef.current = false;
      }
  };

  // Fonction sécurisée pour obtenir les initiales
  const getInitials = (name?: string): string => {
    if (!name || typeof name !== 'string') return "?";

    try {
      return name
        .split(" ")
        .filter(part => part.length > 0)
        .map(n => n[0])
        .join("")
        .toUpperCase()
        .substring(0, 2);
    } catch (error) {
      console.error('❌ Erreur lors de l\'extraction des initiales:', error);
      return "?";
    }
  };

  // Formater la date si elle existe, sinon mettre une valeur par défaut
  const formatCommentDate = (dateString?: string | null): string => {
    if (!dateString) return "Date inconnue";
    try {
      return formatDateTime(dateString);
    } catch (error) {
      console.error('❌ Erreur lors du formatage de la date:', error, dateString);
      return "Date invalide";
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className={`sm:max-w-md bg-white/90 backdrop-blur-md w-[95vw] max-w-[95vw] sm:w-auto sm:max-w-md ${isMobile ? 'p-4' : 'p-6'}`}>
        <DialogHeader>
          <DialogTitle className="font-sans text-xl sm:text-2xl text-trip-blue">Commentaires</DialogTitle>
          <DialogDescription className="text-muted-foreground text-sm">
            Les commentaires permettent d’échanger directement autour d’une étape. Posez une question ou partagez votre retour.
          </DialogDescription>
        </DialogHeader>
        <div className={`max-h-60 sm:max-h-80 overflow-y-auto ${isMobile ? 'px-1' : 'px-2'}`}>
          {isLoading ? (
            <div className="flex justify-center py-6"><Loader2 className="h-5 w-5 animate-spin" /></div>
          ) : loadError ? (
            <p role="alert" className="text-center py-6 text-destructive text-sm">{loadError}</p>
          ) : comments && comments.length > 0 ? (
            <div className="space-y-3 sm:space-y-4 py-2">
              {comments.map((comment) => (
                <div key={comment.id || `temp-${Date.now()}`} className="flex gap-2 sm:gap-3">
                  <Avatar className="h-7 w-7 sm:h-8 sm:w-8 border border-trip-sand">
                    <AvatarImage src={comment.userAvatar || undefined} />
                    <AvatarFallback className="bg-trip-dawn text-trip-orange text-xs sm:text-sm">
                      {getInitials(comment.userName || "?")}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1">
                    <div className="flex justify-between items-center flex-wrap">
                      <span className="font-medium text-trip-blue text-sm">{comment.userName || "Utilisateur inconnu"}</span>
                      <span className="text-muted-foreground text-xs">
                        {formatCommentDate(comment.createdAt)}
                      </span>
                    </div>
                    <p className="text-xs sm:text-sm mt-1 text-foreground break-words">{comment.content || "Pas de contenu disponible"}</p>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-center py-6 text-muted-foreground text-sm">
              Aucun commentaire pour le moment. Lancez la discussion autour de cette étape.
            </p>
          )}
        </div>
        <div className="pt-2">
          <Textarea
            id={`step-comment-${step.id}`}
            autoFocus
            placeholder="Ajoutez un commentaire..."
            value={newComment}
            onChange={(e) => { setNewComment(e.target.value); if (sendFeedback?.type === "success") setSendFeedback(null); }}
            maxLength={COMMENT_MAX_LENGTH}
            className={`min-h-16 sm:min-h-24 bg-white/50 border-trip-sand focus:border-trip-blue text-sm ${isMobile ? 'text-base' : ''}`}
          />
        </div>
        {sendFeedback && <p role={sendFeedback.type === "error" ? "alert" : "status"} className={`text-sm ${sendFeedback.type === "error" ? "text-destructive" : "text-emerald-700"}`}>{sendFeedback.text}</p>}
        <p className="text-right text-xs text-muted-foreground">{newComment.length}/{COMMENT_MAX_LENGTH}</p>
        <DialogFooter className={`flex ${isMobile ? 'flex-col space-y-2' : 'flex-row gap-2'}`}>
          <Button
            type="button"
            variant="outline"
            onClick={onClose}
            className="border-trip-sand hover:bg-trip-dawn hover:text-trip-orange w-full sm:w-auto"
          >
            Fermer
          </Button>
          <Button
            type="button"
            variant="sunset"
            onClick={handleAddComment}
            disabled={!newComment.trim() || isSubmitting}
            className="w-full sm:w-auto"
          >
            {isSubmitting ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" />Publication...</> : "Publier"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
