import React, { useState, useEffect, useRef } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Textarea } from "@/Components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Check, Search, Image as ImageIcon, X } from "lucide-react";

interface NoteFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: () => void;
  initialData?: any;
}

const COLORS = [
  { value: "blue", hex: "#3b82f6" },
  { value: "green", hex: "#22c55e" },
  { value: "red", hex: "#ef4444" },
  { value: "yellow", hex: "#eab308" },
  { value: "purple", hex: "#a855f7" },
];

export function NoteFormModal({ isOpen, onClose, onSave, initialData }: NoteFormModalProps) {
  const [content, setContent] = useState("");
  const [color, setColor] = useState("blue");
  const [isLoading, setIsLoading] = useState(false);
  const [image, setImage] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Search draw
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [selectedDraw, setSelectedDraw] = useState<any>(null);
  const [isSearching, setIsSearching] = useState(false);

  useEffect(() => {
    if (isOpen) {
      if (initialData) {
        setContent(initialData.content || "");
        setColor(initialData.color || "blue");
        setSelectedDraw(initialData.draw || null);
        setImagePreview(initialData.image_url || null);
      } else {
        setContent("");
        setColor("blue");
        setSelectedDraw(null);
        setImagePreview(null);
      }
      setImage(null);
      setSearchQuery("");
      setSearchResults([]);
    }
  }, [isOpen, initialData]);

  useEffect(() => {
    if (!searchQuery.trim()) {
      setSearchResults([]);
      return;
    }
    const delayDebounceFn = setTimeout(() => {
      setIsSearching(true);
      fetch(`/api/search?q=${encodeURIComponent(searchQuery)}`)
        .then(res => res.json())
        .then(data => setSearchResults(data))
        .finally(() => setIsSearching(false));
    }, 300);

    return () => clearTimeout(delayDebounceFn);
  }, [searchQuery]);

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setImage(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setImagePreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleRemoveImage = () => {
    setImage(null);
    setImagePreview(initialData?.image_url || null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleSave = async () => {
    if (!content.trim()) return;
    setIsLoading(true);
    
    const url = initialData ? `/api/notes/${initialData.id}` : '/api/notes';
    // Laravel requires POST method with _method=PUT for multipart/form-data updates
    const method = 'POST'; 

    const formData = new FormData();
    formData.append('content', content);
    formData.append('color', color);
    if (selectedDraw) {
      formData.append('draw_id', selectedDraw.id.toString());
    }
    if (image) {
      formData.append('image', image);
    }
    if (initialData) {
      formData.append('_method', 'PUT');
    }

    try {
      await fetch(url, {
        method,
        body: formData
      });
      onSave();
      onClose();
    } catch (e) {
      console.error(e);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>{initialData ? "Modifier la note" : "Ajouter une note"}</DialogTitle>
        </DialogHeader>
        
        <div className="grid gap-6 py-4 max-h-[70vh] overflow-y-auto pr-2">
          <div className="space-y-4">
            <h3 className="text-lg font-medium">Détails de la note</h3>
            <div className="h-px bg-border" />
          </div>

          <div className="grid gap-2">
            <label className="text-sm font-medium">Code couleur</label>
            <Select value={color} onValueChange={setColor}>
              <SelectTrigger>
                <SelectValue>
                  <div className="flex items-center gap-2">
                    <div className="h-3 w-3 rounded-full" style={{ backgroundColor: COLORS.find(c => c.value === color)?.hex }} />
                  </div>
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                {COLORS.map(c => (
                  <SelectItem key={c.value} value={c.value}>
                    <div className="flex items-center gap-2">
                      <div className="h-3 w-3 rounded-full" style={{ backgroundColor: c.hex }} />
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="grid gap-2">
            <label className="text-sm font-medium">Tirage associé (Optionnel)</label>
            {selectedDraw ? (
              <div className="flex items-center justify-between p-2 rounded-md border border-border bg-muted">
                <span className="text-sm font-medium">{selectedDraw.name} {selectedDraw.draw_date ? `(${new Date(selectedDraw.draw_date).toLocaleDateString()})` : ''}</span>
                <Button variant="ghost" size="sm" onClick={() => setSelectedDraw(null)}>Retirer</Button>
              </div>
            ) : (
              <div className="relative">
                <div className="flex items-center gap-2 rounded-md border border-border px-3 py-2 focus-within:ring-1 focus-within:ring-ring">
                  <Search className="h-4 w-4 text-muted-foreground shrink-0" />
                  <input
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Rechercher un tirage..."
                    className="w-full bg-transparent text-sm focus:outline-none"
                  />
                </div>
                {searchResults.length > 0 && (
                  <div className="absolute top-full z-50 w-full bg-popover mt-1 border border-border rounded-md shadow-md max-h-48 overflow-y-auto">
                    {searchResults.map((result, idx) => (
                      <div 
                        key={idx}
                        className="px-3 py-2 text-sm hover:bg-muted cursor-pointer"
                        onClick={() => {
                          setSelectedDraw(result);
                          setSearchQuery("");
                          setSearchResults([]);
                        }}
                      >
                        {result.name} <span className="text-muted-foreground">({new Date(result.draw_date).toLocaleDateString()})</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>

          <div className="grid gap-2">
            <label className="text-sm font-medium">Image (Optionnel)</label>
            <div className="flex flex-col gap-4">
              <input 
                type="file" 
                accept="image/*" 
                className="hidden" 
                ref={fileInputRef} 
                onChange={handleImageChange} 
              />
              {!imagePreview ? (
                <div 
                  className="flex flex-col items-center justify-center border-2 border-dashed border-border rounded-xl p-6 cursor-pointer hover:bg-muted/50 transition-colors"
                  onClick={() => fileInputRef.current?.click()}
                >
                  <ImageIcon className="h-8 w-8 text-muted-foreground mb-2" />
                  <span className="text-sm text-muted-foreground">Cliquez pour ajouter une image</span>
                </div>
              ) : (
                <div className="relative rounded-xl overflow-hidden border border-border bg-muted w-full max-w-[200px]">
                  <img src={imagePreview} alt="Aperçu" className="w-full h-auto object-cover" />
                  <button 
                    onClick={handleRemoveImage}
                    className="absolute top-2 right-2 p-1 bg-black/60 hover:bg-black text-white rounded-full transition-colors"
                  >
                    <X className="h-4 w-4" />
                  </button>
                </div>
              )}
            </div>
          </div>

          <div className="grid gap-2">
            <label className="text-sm font-medium">Note</label>
            <Textarea 
              value={content}
              onChange={(e) => setContent(e.target.value)}
              className="min-h-[120px]"
              placeholder="Saisissez votre note ici..."
            />
          </div>
        </div>

        <DialogFooter className="gap-2 sm:justify-start">
          <Button onClick={handleSave} disabled={isLoading || !content.trim()}>
            <Check className="mr-2 h-4 w-4" />
            Sauvegarder
          </Button>
          <Button variant="ghost" onClick={onClose} disabled={isLoading}>
            Annuler
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
