import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { FileText, Loader2, RefreshCw, Eye } from "lucide-react";
import { format } from "date-fns";
import { Alert, AlertDescription } from "@/components/ui/alert";
import ArcApplicationDetail from "@/components/arc/ArcApplicationDetail";

export default function UnitArcApplicationsTab({ unitId }: { unitId: string }) {
  const [applications, setApplications] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedApp, setSelectedApp] = useState<any | null>(null);

  const fetchApplications = async () => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: fetchError } = await supabase
        .from("arc_applications")
        .select("*")
        .eq("unit_id", unitId)
        .order("created_at", { ascending: false });

      if (fetchError) throw fetchError;
      setApplications(data || []);
    } catch (err: any) {
      console.error("Error fetching ARC apps:", err);
      setError(err.message || "Failed to fetch applications");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (unitId) fetchApplications();
  }, [unitId]);

  const getStatusColor = (status: string | null) => {
    switch ((status || "").toLowerCase()) {
      case "approved": return "bg-success/20 text-success-foreground";
      case "rejected": case "denied": return "bg-destructive/20 text-destructive";
      case "pending": case "submitted": return "bg-warning/20 text-warning-foreground";
      default: return "bg-muted text-muted-foreground";
    }
  };

  if (loading) return <div className="flex justify-center p-8"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>;

  if (error) {
    return (
      <Alert variant="destructive">
        <FileText className="w-4 h-4" />
        <AlertDescription className="flex items-center justify-between">
          <span>{error}</span>
          <Button variant="outline" size="sm" onClick={fetchApplications}><RefreshCw className="w-4 h-4 mr-2" /> Retry</Button>
        </AlertDescription>
      </Alert>
    );
  }

  return (
    <div className="space-y-4">
      {applications.length === 0 ? (
        <div className="text-center p-8 bg-muted rounded-lg border">
          <FileText className="w-8 h-8 text-muted-foreground mx-auto mb-3" />
          <p className="font-medium">No ARC Applications</p>
          <p className="text-sm text-muted-foreground mt-1">There are no architectural requests for this unit.</p>
        </div>
      ) : (
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Title</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {applications.map((app) => (
                <TableRow key={app.id}>
                  <TableCell className="whitespace-nowrap">{app.created_at ? format(new Date(app.created_at), "MMM d, yyyy") : "N/A"}</TableCell>
                  <TableCell className="font-medium">{app.title || "Untitled Application"}</TableCell>
                  <TableCell><Badge variant="secondary" className={getStatusColor(app.status)}>{app.status || "Pending"}</Badge></TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="sm" onClick={() => setSelectedApp(app)}><Eye className="w-4 h-4 mr-2" /> View</Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <Dialog open={!!selectedApp} onOpenChange={(open) => !open && setSelectedApp(null)}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2"><FileText className="w-5 h-5 text-muted-foreground" /> ARC Application Details</DialogTitle>
          </DialogHeader>
          {selectedApp && <ArcApplicationDetail application={selectedApp} onStatusChange={fetchApplications} />}
        </DialogContent>
      </Dialog>
    </div>
  );
}