import React, { useEffect, useState } from "react";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/Components/ui/sheet";
import { Button } from "@/Components/ui/button";
import { Plus, MoreHorizontal, StickyNote, Eye, Edit2, Trash2 } from "lucide-react";
import { NoteFormModal } from "./NoteFormModal";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/Components/ui/dropdown-menu";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/Components/ui/dialog";

interface Note {
  id: number;
  content: string;
  color: string;
  draw_id: number | null;
  draw?: any;
  image_url?: string;
  created_at: string;
}

const COLORS: Record<string, string> = {
  blue: "bg-blue-500",
  green: "bg-green-500",
  red: "bg-red-500",
  yellow: "bg-yellow-500",
  purple: "bg-purple-500",
};

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

export function NotesPanel({ isOpen, onClose }: NotesPanelProps) {
  const [notes, setNotes] = useState<Note[]>([]);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [noteToEdit, setNoteToEdit] = useState<Note | null>(null);
  const [noteToView, setNoteToView] = useState<Note | null>(null);

  const fetchNotes = async () => {
    try {
      const res = await fetch('/api/notes');
      const data = await res.json();
      setNotes(data);
    } catch (e) {
      console.error("Failed to fetch notes", e);
    }
  };

  useEffect(() => {
    if (isOpen) {
      fetchNotes();
    }
  }, [isOpen]);

  const handleDelete = async (id: number) => {
    if (!confirm("Voulez-vous vraiment supprimer cette note ?")) return;
    try {
      await fetch(`/api/notes/${id}`, { method: 'DELETE' });
      fetchNotes();
    } catch (e) {
      console.error(e);
    }
  };

  return (
    <>
      <Sheet open={isOpen} onOpenChange={onClose}>
        <SheetContent side="left" className="w-[400px] sm:w-[540px] bg-sidebar border-r-0 p-6 flex flex-col">
          <SheetHeader className="mb-6 flex flex-row items-center justify-between">
            <SheetTitle className="text-xl font-display text-sidebar-foreground">Notes autocollantes</SheetTitle>
          </SheetHeader>

          <Button 
            className="w-auto self-start bg-sidebar-foreground text-sidebar hover:bg-sidebar-foreground/90 mb-6" 
            onClick={() => setIsFormOpen(true)}
          >
            <Plus className="mr-2 h-4 w-4" /> Ajouter Une Note
          </Button>

          <div className="flex-1 overflow-y-auto space-y-4 pr-2">
            {notes.map(note => (
              <div key={note.id} className="relative rounded-xl border border-border bg-card p-4">
                <div className="flex justify-between items-start mb-12">
                  <div className="flex flex-col gap-3 flex-1 mr-4">
                    {note.image_url && (
                      <div className="w-full h-32 rounded-lg overflow-hidden border border-border">
                        <img src={note.image_url} alt="Note image" className="w-full h-full object-cover" />
                      </div>
                    )}
                    <p className="text-sm text-card-foreground whitespace-pre-wrap">{note.content.length > 100 ? note.content.substring(0, 100) + '...' : note.content}</p>
                    {note.draw && (
                      <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 text-xs font-medium text-muted-foreground ring-1 ring-inset ring-border w-max">
                        {note.draw.name}
                      </span>
                    )}
                  </div>
                  
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="h-6 w-6 shrink-0">
                        <MoreHorizontal className="h-4 w-4 text-muted-foreground" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem onClick={() => setNoteToView(note)}>
                        <Eye className="mr-2 h-4 w-4" /> Voir
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => setNoteToEdit(note)}>
                        <Edit2 className="mr-2 h-4 w-4" /> Modifier
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => handleDelete(note.id)} className="text-destructive">
                        <Trash2 className="mr-2 h-4 w-4" /> Supprimer
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
                <div className="flex justify-between items-center mt-4">
                  <span className="text-xs text-muted-foreground">
                    {new Date(note.created_at).toLocaleDateString('fr-FR', {
                      day: '2-digit', month: '2-digit', year: 'numeric'
                    }).replace(/\//g, '-')}
                  </span>
                  <div className={`h-3 w-3 rounded-full ${COLORS[note.color] || "bg-blue-500"}`} />
                </div>
              </div>
            ))}
            {notes.length === 0 && (
              <div className="text-center py-10 text-muted-foreground flex flex-col items-center">
                <StickyNote className="h-10 w-10 mb-4 opacity-20" />
                <p>Aucune note pour le moment.</p>
              </div>
            )}
          </div>
        </SheetContent>
      </Sheet>
      
      <NoteFormModal 
        isOpen={isFormOpen || !!noteToEdit} 
        onClose={() => {
          setIsFormOpen(false);
          setNoteToEdit(null);
        }} 
        onSave={fetchNotes} 
        initialData={noteToEdit}
      />

      <Dialog open={!!noteToView} onOpenChange={() => setNoteToView(null)}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Détails de la note</DialogTitle>
          </DialogHeader>
          {noteToView && (
            <div className="space-y-4 py-4">
              <div className="flex items-center gap-2">
                <div className={`h-3 w-3 rounded-full ${COLORS[noteToView.color] || "bg-blue-500"}`} />
                <span className="text-sm font-medium">
                  {new Date(noteToView.created_at).toLocaleDateString('fr-FR', {
                    day: '2-digit', month: '2-digit', year: 'numeric',
                    hour: '2-digit', minute: '2-digit'
                  })}
                </span>
              </div>
              
              {noteToView.draw && (
                <div>
                  <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 text-xs font-medium text-muted-foreground ring-1 ring-inset ring-border w-max">
                    Tirage: {noteToView.draw.name}
                  </span>
                </div>
              )}

              {noteToView.image_url && (
                <div className="w-full rounded-xl overflow-hidden border border-border">
                  <img src={noteToView.image_url} alt="Note image" className="w-full h-auto object-contain max-h-[400px]" />
                </div>
              )}
              
              <div className="p-4 rounded-xl border border-border bg-muted/50 text-foreground whitespace-pre-wrap">
                {noteToView.content}
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}
