import React, { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Settings, Bell, ListPlus, SlidersHorizontal, Check, GripVertical, Trash2 } from "lucide-react";
import { router, usePage } from "@inertiajs/react";

interface SettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
  const [activeTab, setActiveTab] = useState("noms");
  const { drawNames } = usePage().props as any;
  const names = drawNames || [];
  
  const [localNames, setLocalNames] = useState<string[]>(names);
  useEffect(() => {
    setLocalNames(names);
  }, [names]);

  const [newName, setNewName] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const [isDeleting, setIsDeleting] = useState<string | null>(null);
  const [isSavingOrder, setIsSavingOrder] = useState(false);

  const [draggedItem, setDraggedItem] = useState<string | null>(null);

  const hasOrderChanges = JSON.stringify(names) !== JSON.stringify(localNames);

  const handleAddName = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newName.trim()) return;
    
    setIsSaving(true);
    try {
      const res = await fetch('/api/draw-names', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify({ name: newName.trim() })
      });
      
      if (res.ok) {
        setNewName("");
        setSaveSuccess(true);
        setTimeout(() => setSaveSuccess(false), 3000);
        router.reload({ only: ['drawNames'] });
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsSaving(false);
    }
  };

  const handleDeleteName = async (nameToDelete: string) => {
    if (!confirm(`Voulez-vous vraiment supprimer le nom "${nameToDelete}" ?`)) return;

    setIsDeleting(nameToDelete);
    try {
      const res = await fetch(`/api/draw-names/${encodeURIComponent(nameToDelete)}`, {
        method: 'DELETE',
        headers: {
          'Accept': 'application/json',
        }
      });
      
      if (res.ok) {
        router.reload({ only: ['drawNames'] });
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsDeleting(null);
    }
  };

  const handleDragStart = (e: React.DragEvent<HTMLDivElement>, name: string) => {
    setDraggedItem(name);
    setTimeout(() => {
      if (e.target instanceof HTMLElement) {
        e.target.style.opacity = "0.5";
      }
    }, 0);
  };

  const handleDragEnd = (e: React.DragEvent<HTMLDivElement>) => {
    if (e.target instanceof HTMLElement) {
      e.target.style.opacity = "1";
    }
    setDraggedItem(null);
  };

  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>, targetName: string) => {
    e.preventDefault();
    if (!draggedItem || draggedItem === targetName) return;

    const currentNames = [...localNames];
    const draggedIdx = currentNames.indexOf(draggedItem);
    const targetIdx = currentNames.indexOf(targetName);

    currentNames.splice(draggedIdx, 1);
    currentNames.splice(targetIdx, 0, draggedItem);

    setLocalNames(currentNames);
  };

  const handleSaveOrder = async () => {
    setIsSavingOrder(true);
    try {
      const res = await fetch('/api/draw-names/reorder', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ names: localNames })
      });
      if (res.ok) {
        router.reload({ only: ['drawNames'] });
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsSavingOrder(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[800px] p-0 overflow-hidden bg-background">
        <div className="flex h-[600px]">
          {/* Sidebar Tabs */}
          <div className="w-[220px] border-r border-border bg-muted/30 p-4 flex flex-col gap-2 shrink-0">
            <h3 className="font-semibold text-lg mb-4 text-foreground flex items-center gap-2">
              <Settings className="w-5 h-5" /> Paramètres
            </h3>
            
            <button
              onClick={() => setActiveTab("noms")}
              className={`flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
                activeTab === "noms" 
                  ? "bg-primary text-primary-foreground font-medium" 
                  : "text-muted-foreground hover:bg-muted hover:text-foreground"
              }`}
            >
              <ListPlus className="w-4 h-4" /> Paramètres des Tirages
            </button>
            
            <button
              onClick={() => setActiveTab("notifications")}
              className={`flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
                activeTab === "notifications" 
                  ? "bg-primary text-primary-foreground font-medium" 
                  : "text-muted-foreground hover:bg-muted hover:text-foreground"
              }`}
            >
              <Bell className="w-4 h-4" /> Notifications
            </button>
          </div>

          {/* Content Area */}
          <div className="flex-1 p-6 overflow-y-auto">
            {activeTab === "noms" && (
              <div className="space-y-6 animate-in fade-in slide-in-from-right-4 duration-300">
                <div>
                  <h4 className="text-lg font-medium">Paramètres des Tirages</h4>
                  <p className="text-sm text-muted-foreground">
                    Ajoutez ou modifiez l'ordre des noms pour qu'ils soient disponibles lors de la saisie manuelle de tirages. Glissez-déposez pour réorganiser.
                  </p>
                </div>
                
                <form onSubmit={handleAddName} className="flex items-end gap-3 p-4 border border-border rounded-xl bg-card">
                  <div className="flex-1 space-y-2">
                    <Label htmlFor="new-name">Ajouter un nom (ex: Réveil)</Label>
                    <Input 
                      id="new-name" 
                      value={newName} 
                      onChange={e => setNewName(e.target.value)} 
                      placeholder="Nouveau nom..."
                      required
                    />
                  </div>
                  <Button type="submit" disabled={isSaving || !newName.trim()}>
                    {isSaving ? "Ajout..." : "Ajouter"}
                  </Button>
                </form>

                {saveSuccess && (
                  <div className="text-sm text-green-600 flex items-center gap-2">
                    <Check className="w-4 h-4" /> Nom ajouté avec succès !
                  </div>
                )}

                <div className="flex items-center justify-between mb-4">
                  <h4 className="text-lg font-medium">Réorganisation</h4>
                  {hasOrderChanges && (
                    <Button onClick={handleSaveOrder} disabled={isSavingOrder} size="sm" className="bg-green-600 hover:bg-green-700">
                      {isSavingOrder ? "Enregistrement..." : "Enregistrer l'ordre"}
                    </Button>
                  )}
                </div>

                <div className="space-y-2">
                  {localNames.map((name: string) => (
                    <div 
                      key={name} 
                      draggable
                      onDragStart={(e) => handleDragStart(e, name)}
                      onDragEnd={handleDragEnd}
                      onDragOver={handleDragOver}
                      onDrop={(e) => handleDrop(e, name)}
                      className={`flex items-center justify-between p-3 rounded-lg border border-border bg-card transition-colors ${draggedItem === name ? 'shadow-md ring-1 ring-primary' : 'hover:bg-muted/50'}`}
                    >
                      <div className="flex items-center gap-3">
                        <div className="cursor-grab hover:text-foreground text-muted-foreground active:cursor-grabbing">
                          <GripVertical className="h-5 w-5" />
                        </div>
                        <span className="font-medium text-sm">{name}</span>
                      </div>
                      <Button 
                        variant="ghost" 
                        size="icon" 
                        className="text-muted-foreground hover:text-destructive hover:bg-destructive/10 h-8 w-8"
                        onClick={() => handleDeleteName(name)}
                        disabled={isDeleting === name}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  ))}
                  {localNames.length === 0 && (
                     <div className="text-center py-6 text-muted-foreground text-sm">
                       Aucun nom de tirage. Ajoutez-en un au-dessus.
                     </div>
                  )}
                </div>

              </div>
            )}

            {activeTab === "notifications" && (
              <div className="space-y-6 animate-in fade-in slide-in-from-right-4 duration-300">
                <div>
                  <h4 className="text-lg font-medium">Paramètres de notification</h4>
                  <p className="text-sm text-muted-foreground">Gérez vos alertes et préférences de communication.</p>
                </div>
                <div className="p-8 text-center border border-dashed border-border rounded-xl text-muted-foreground">
                  <Bell className="w-8 h-8 mx-auto mb-3 opacity-20" />
                  <p>Options de notification à venir.</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
