import React, { useEffect, useState } from 'react';
import { format } from 'date-fns';
import { Loader2, FileText, Trash2, Calendar, User } from 'lucide-react';
import {
  Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import DeleteReportDialog from './DeleteReportDialog';
import { cn } from '@/lib/utils';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export default function LoadReportDialog({ open, onOpenChange, onLoad }) {
  const { toast } = useToast();
  const [reports, setReports] = useState([]);
  const [loading, setLoading] = useState(false);
  const [deleteReportId, setDeleteReportId] = useState(null);
  const [reportToDelete, setReportToDelete] = useState(null);

  const fetchReports = async () => {
    setLoading(true);
    // Placeholder: adjust table/columns as needed
    const { data, error } = await supabase
      .from('documents')
      .select('*')
      .order('created_at', { ascending: false });
    if (data) setReports(data);
    if (error) toast({ variant: 'destructive', title: 'Error', description: error.message });
    setLoading(false);
  };

  useEffect(() => {
    if (open) {
      fetchReports();
    }
  }, [open]);

  const handleDeleteClick = (e, report) => {
    e.stopPropagation();
    setReportToDelete(report);
    setDeleteReportId(report.id);
  };

  const handleConfirmDelete = async (id) => {
    const { error } = await supabase.from('documents').delete().eq('id', id);
    if (error) toast({ variant: 'destructive', title: 'Error', description: error.message });
    else {
      toast({ title: 'Report deleted' });
      fetchReports();
    }
    setReportToDelete(null);
    setDeleteReportId(null);
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[600px] h-[80vh] flex flex-col p-0 gap-0">
          <DialogHeader className="p-6 pb-4 border-b">
            <DialogTitle>Load Saved Report</DialogTitle>
            <DialogDescription>Select a previously saved report configuration to load.</DialogDescription>
          </DialogHeader>
          
          <div className="flex-1 overflow-hidden relative">
            {loading && reports.length === 0 ? (
              <div className="absolute inset-0 flex items-center justify-center bg-background z-10">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
              </div>
            ) : reports.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full text-muted-foreground p-8 text-center">
                <FileText className="h-12 w-12 mb-3 opacity-20" />
                <p>No saved reports found.</p>
              </div>
            ) : (
              <ScrollArea className="h-full">
                <div className="p-4 space-y-3">
                  {reports.map((report) => (
                    <div
                      key={report.id}
                      onClick={() => onLoad(report)}
                      className="group flex flex-col sm:flex-row sm:items-center justify-between p-4 rounded-lg border bg-card hover:border-primary/30 hover:shadow-md hover:bg-accent/30 transition-all cursor-pointer"
                    >
                      <div className="flex-1 min-w-0 mb-3 sm:mb-0">
                        <div className="flex items-center gap-2 mb-1">
                          <h4 className="font-semibold truncate">{report.title}</h4>
                        </div>
                        <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground">
                          <div className="flex items-center gap-1.5">
                            <Calendar className="h-3.5 w-3.5" />
                            <span>{format(new Date(report.created_at), 'MMM d, yyyy')}</span>
                          </div>
                        </div>
                      </div>
                      
                      <div className="flex items-center gap-2 pl-0 sm:pl-4 sm:border-l">
                         <Button variant="ghost" size="sm" className="hidden sm:flex text-primary hover:bg-primary/10">Load</Button>
                         <Button
                          variant="ghost"
                          size="icon"
                          className="text-muted-foreground hover:text-destructive hover:bg-destructive/10"
                          onClick={(e) => handleDeleteClick(e, report)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </ScrollArea>
            )}
          </div>
        </DialogContent>
      </Dialog>

      <DeleteReportDialog
        open={!!deleteReportId}
        onOpenChange={(isOpen) => !isOpen && setDeleteReportId(null)}
        report={reportToDelete}
        onConfirm={handleConfirmDelete}
        isDeleting={loading}
      />
    </>
  );
}
