import React, { useState } from 'react';
import { Trash2, File, Folder, RotateCcw, RefreshCw } from 'lucide-react';
import { useEditorStore } from '@/core/store';
import { notesApi, foldersApi } from '@/lib/api';
import { Button } from '@/components/ui/button';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { motion } from 'framer-motion';
import { appleListItem, appleSpringGentle } from '@/lib/apple-animations';
import { toast } from 'sonner';

export const TrashPanel: React.FC = () => {
  const { loadFiles, activeSidebarPanel } = useEditorStore();
  const [deletedNotes, setDeletedNotes] = useState<any[]>([]);
  const [deletedFolders, setDeletedFolders] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [emptyTrashDialogOpen, setEmptyTrashDialogOpen] = useState(false);
  const [singleDeleteItem, setSingleDeleteItem] = useState<{ id: string; type: 'file' | 'folder'; name: string } | null>(null);

  React.useEffect(() => {
    loadDeletedItems();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Refresh deleted items when trash panel becomes active
  React.useEffect(() => {
    if (activeSidebarPanel === 'trash') {
      loadDeletedItems();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeSidebarPanel]);

  const loadDeletedItems = async () => {
    try {
      setIsLoading(true);
      // Load both deleted notes and folders (don't swallow errors so we can show a message)
      const [notesResponse, foldersResponse] = await Promise.all([
        notesApi.getDeleted().catch((err) => {
          console.error('Failed to load deleted notes:', err);
          toast.error('Failed to load trash. Check console.');
          return { notes: [] };
        }),
        foldersApi.getDeleted().catch((err) => {
          console.error('Failed to load deleted folders:', err);
          toast.error('Failed to load trash. Check console.');
          return { folders: [] };
        }),
      ]);
      // Handle both { notes: [] } and raw array (in case backend shape differs)
      const notes = Array.isArray(notesResponse) ? notesResponse : (notesResponse?.notes ?? []);
      const folders = Array.isArray(foldersResponse) ? foldersResponse : (foldersResponse?.folders ?? []);
      setDeletedNotes(notes);
      setDeletedFolders(folders);
    } catch (error) {
      console.error('Failed to load deleted items:', error);
      toast.error('Failed to load trash');
    } finally {
      setIsLoading(false);
    }
  };

  // Combine notes and folders, sorted by deletion date
  const deletedItems = React.useMemo(() => {
    const allItems = [
      ...deletedNotes.map(note => ({ ...note, type: 'file' as const })),
      ...deletedFolders.map(folder => ({ ...folder, type: 'folder' as const })),
    ];
    return allItems.sort((a, b) => {
      const dateA = a.deleted_at ? new Date(a.deleted_at).getTime() : 0;
      const dateB = b.deleted_at ? new Date(b.deleted_at).getTime() : 0;
      return dateB - dateA; // Most recent first
    });
  }, [deletedNotes, deletedFolders]);

  const handleRestore = async (id: string, type: 'file' | 'folder') => {
    try {
      if (type === 'file') {
        await notesApi.restore(id);
        toast.success('Note restored');
      } else {
        await foldersApi.restore(id);
        toast.success('Folder restored');
      }
      await loadDeletedItems();
      await loadFiles();
    } catch (error) {
      console.error('Failed to restore:', error);
      toast.error('Failed to restore item');
    }
  };

  const handlePermanentDelete = async (id: string, type: 'file' | 'folder') => {
    try {
      if (type === 'file') {
        await notesApi.permanentDelete(id);
        toast.success('Note permanently deleted');
      } else {
        await foldersApi.permanentDelete(id);
        toast.success('Folder permanently deleted');
      }
      await loadDeletedItems();
      await loadFiles();
    } catch (error) {
      console.error('Failed to delete:', error);
      toast.error('Failed to delete item');
    } finally {
      setSingleDeleteItem(null);
    }
  };

  const handleEmptyTrash = async () => {
    try {
      // Empty both notes and folders trash
      await Promise.all([
        notesApi.emptyTrash(),
        foldersApi.emptyTrash(),
      ]);
      toast.success('Trash emptied successfully');
      await loadDeletedItems();
      await loadFiles();
      setEmptyTrashDialogOpen(false);
    } catch (error) {
      console.error('Failed to empty trash:', error);
      toast.error('Failed to empty trash');
    }
  };

  return (
    <div className="h-full flex flex-col">
      <div className="flex items-center justify-between px-3 py-2 border-b border-sidebar-border">
        <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
          Trash
        </span>
        <div className="flex items-center gap-1">
          <Button
            variant="ghost"
            size="icon"
            className="h-6 w-6"
            onClick={() => loadDeletedItems()}
            title="Refresh"
            disabled={isLoading}
          >
            <RefreshCw className={`w-3 h-3 ${isLoading ? 'animate-spin' : ''}`} />
          </Button>
          {deletedItems.length > 0 && (
            <Button
              variant="ghost"
              size="sm"
              className="h-6 text-xs"
              onClick={() => setEmptyTrashDialogOpen(true)}
            >
              Empty Trash
            </Button>
          )}
        </div>
      </div>

      <div className="flex-1 overflow-auto py-1 apple-scroll flex flex-col min-h-0">
        {isLoading ? (
          <div className="px-3 py-8 text-center text-muted-foreground text-sm">
            <div className="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-2" />
            <p>Loading...</p>
          </div>
        ) : deletedItems.length === 0 ? (
          <div className="flex-1 flex flex-col items-center justify-center px-6 py-12 min-h-0">
            <div className="w-20 h-20 rounded-2xl bg-muted/50 border border-border flex items-center justify-center mb-4">
              <Trash2 className="w-10 h-10 text-muted-foreground/60" />
            </div>
            <h3 className="text-sm font-medium text-foreground mb-1">Trash is empty</h3>
            <p className="text-xs text-muted-foreground text-center max-w-[200px] mb-2">
              Deleted notes and folders appear here. Restore or permanently remove them.
            </p>
            <p className="text-[11px] text-muted-foreground/70">
              Items stay until you empty trash.
            </p>
          </div>
        ) : (
          deletedItems.map((item) => (
            <motion.div
              key={item.id}
              {...appleListItem}
              transition={appleSpringGentle}
              className="group flex items-center gap-2 px-3 py-2 hover:bg-sidebar-accent"
            >
              {item.type === 'folder' ? (
                <Folder className="w-4 h-4 text-muted-foreground flex-shrink-0" />
              ) : (
                <File className="w-4 h-4 text-muted-foreground flex-shrink-0" />
              )}
              <div className="flex-1 min-w-0">
                <p className="text-sm truncate">{item.title || item.name}</p>
                <p className="text-xs text-muted-foreground">
                  Deleted {item.deleted_at ? new Date(item.deleted_at).toLocaleDateString() : ''}
                </p>
              </div>
              <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6"
                  onClick={() => handleRestore(item.id, item.type)}
                  title="Restore"
                >
                  <RotateCcw className="w-3 h-3" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6 text-destructive"
                  onClick={() => setSingleDeleteItem({ id: item.id, type: item.type, name: item.title || item.name })}
                  title="Delete Permanently"
                >
                  <Trash2 className="w-3 h-3" />
                </Button>
              </div>
            </motion.div>
          ))
        )}
      </div>

      {/* Single item permanent delete confirmation */}
      <AlertDialog open={!!singleDeleteItem} onOpenChange={(open) => !open && setSingleDeleteItem(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete permanently?</AlertDialogTitle>
            <AlertDialogDescription>
              Permanently delete <strong>{singleDeleteItem?.name ?? ''}</strong>? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => singleDeleteItem && handlePermanentDelete(singleDeleteItem.id, singleDeleteItem.type)}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Empty Trash Confirmation Dialog */}
      <AlertDialog open={emptyTrashDialogOpen} onOpenChange={setEmptyTrashDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Empty Trash?</AlertDialogTitle>
            <AlertDialogDescription>
              This will permanently delete all items in trash ({deletedItems.length} item{deletedItems.length !== 1 ? 's' : ''}).
              This action cannot be undone. Are you sure you want to continue?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleEmptyTrash}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Empty Trash
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default TrashPanel;
