import { useEffect, useMemo, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Gavel, RefreshCw, FileText, Clock, CheckCircle2, XCircle, AlertCircle, Eye } from "lucide-react";
import { format } from "date-fns";
import VotingAndComments from "@/components/shared/VotingAndComments";

const STATUS_CONFIG: Record<string, { label: string; cls: string; icon: React.ElementType }> = {
  submitted:        { label: "Submitted",        cls: "bg-blue-100 text-blue-700 border-blue-200",         icon: FileText },
  pending:          { label: "Pending",          cls: "bg-blue-100 text-blue-700 border-blue-200",         icon: FileText },
  under_review:     { label: "Under Review",     cls: "bg-amber-100 text-amber-700 border-amber-200",      icon: Clock },
  awaiting_changes: { label: "Awaiting Changes", cls: "bg-orange-100 text-orange-700 border-orange-200",  icon: AlertCircle },
  approved:         { label: "Approved",         cls: "bg-emerald-100 text-emerald-700 border-emerald-200", icon: CheckCircle2 },
  denied:           { label: "Denied",           cls: "bg-red-100 text-red-700 border-red-200",            icon: XCircle },
  withdrawn:        { label: "Withdrawn",        cls: "bg-muted text-muted-foreground border-border",     icon: XCircle },
};
const getStatus = (s: string | null) => STATUS_CONFIG[s || "pending"] || STATUS_CONFIG.pending;
const PENDING_STATUSES = ["submitted", "pending", "under_review", "awaiting_changes"];

export default function ArcCommitteePage() {
  const { user } = useAuth();
  const [apps, setApps] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [noCommittee, setNoCommittee] = useState(false);
  const [statusFilter, setStatusFilter] = useState<"pending" | "all" | "approved" | "denied">("pending");
  const [assocFilter, setAssocFilter] = useState<string>("all");
  const [selected, setSelected] = useState<any | null>(null);

  const fetchApps = async () => {
    if (!user?.email) { setLoading(false); return; }
    setLoading(true);
    setNoCommittee(false);
    const { data, error } = await supabase.functions.invoke("arc-committee-reviews");
    if (error) {
      console.error("Failed to load ARC reviews", error);
      setApps([]);
      setNoCommittee(false);
      setLoading(false);
      return;
    }
    setApps(data?.applications || []);
    setNoCommittee(!!data?.noCommittee);
    setLoading(false);
  };

  useEffect(() => { fetchApps(); }, [user?.email]);

  const associations = useMemo(() => {
    const map = new Map<string, string>();
    apps.forEach((a) => { if (a.association_id) map.set(a.association_id, a.associations?.name || "—"); });
    return Array.from(map.entries()).map(([id, name]) => ({ id, name }));
  }, [apps]);

  const filtered = useMemo(() => {
    return apps.filter((a) => {
      const st = (a.status || "pending").toLowerCase();
      if (statusFilter === "pending" && !PENDING_STATUSES.includes(st)) return false;
      if (statusFilter === "approved" && st !== "approved") return false;
      if (statusFilter === "denied" && st !== "denied") return false;
      if (assocFilter !== "all" && a.association_id !== assocFilter) return false;
      return true;
    });
  }, [apps, statusFilter, assocFilter]);

  const ownerName = (a: any) => a.owners ? `${a.owners.first_name} ${a.owners.last_name}` : "—";
  const propertyAddr = (a: any) => a.units?.address || a.owners?.property_address || a.units?.unit_number || "—";

  return (
    <div className="space-y-5">
      <div className="flex items-start justify-between flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10">
            <Gavel className="h-5 w-5 text-primary" />
          </div>
          <div>
            <h1 className="text-[22px] font-bold tracking-tight text-foreground">ARC Applications to Review</h1>
            <p className="text-[13px] text-muted-foreground">Cast your vote and add comments on pending architectural review requests.</p>
          </div>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <Select value={statusFilter} onValueChange={(v: any) => setStatusFilter(v)}>
            <SelectTrigger className="h-8 w-[160px] text-[12px]"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="pending">Pending Review</SelectItem>
              <SelectItem value="approved">Approved</SelectItem>
              <SelectItem value="denied">Denied</SelectItem>
              <SelectItem value="all">All</SelectItem>
            </SelectContent>
          </Select>
          {associations.length > 1 && (
            <Select value={assocFilter} onValueChange={setAssocFilter}>
              <SelectTrigger className="h-8 w-[200px] text-[12px]"><SelectValue placeholder="Association" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Associations</SelectItem>
                {associations.map((a) => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
              </SelectContent>
            </Select>
          )}
          <Button variant="outline" size="sm" className="gap-1.5 h-8 text-[12px]" onClick={fetchApps}>
            <RefreshCw className="h-3.5 w-3.5" /> Refresh
          </Button>
        </div>
      </div>

      {loading ? (
        <div className="flex justify-center py-16">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
        </div>
      ) : (
        <Card>
          <CardContent className="p-0">
            {noCommittee && (
              <div className="p-8 text-center">
                <Gavel className="h-8 w-8 text-muted-foreground mx-auto mb-3" />
                <p className="font-medium">You're not on any ARC committee yet</p>
                <p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">
                  Your ARC member role is set, but your email <span className="font-medium">{user?.email}</span> isn't listed as an active committee member for any association. Ask your association manager to add you to the ARC committee so you can view and vote on applications.
                </p>
              </div>
            )}
            {!noCommittee && (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Submitted</TableHead>
                  <TableHead>Project</TableHead>
                  <TableHead>Owner</TableHead>
                  <TableHead>Property</TableHead>
                  <TableHead>Association</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filtered.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-12 text-muted-foreground">
                      No applications match your filters.
                    </TableCell>
                  </TableRow>
                ) : filtered.map((a) => {
                  const st = getStatus(a.status);
                  const Icon = st.icon;
                  return (
                    <TableRow key={a.id}>
                      <TableCell className="text-sm whitespace-nowrap">
                        {a.submitted_date ? format(new Date(a.submitted_date), "MMM d, yyyy") : a.created_at ? format(new Date(a.created_at), "MMM d, yyyy") : "—"}
                      </TableCell>
                      <TableCell>
                        <p className="font-medium">{a.title || "Untitled"}</p>
                        {a.project_type && <p className="text-xs text-muted-foreground">{a.project_type}</p>}
                      </TableCell>
                      <TableCell className="text-sm">{ownerName(a)}</TableCell>
                      <TableCell className="text-sm">{propertyAddr(a)}</TableCell>
                      <TableCell className="text-sm">{a.associations?.name || "—"}</TableCell>
                      <TableCell>
                        <Badge variant="outline" className={`gap-1 ${st.cls}`}>
                          <Icon className="h-3 w-3" /> {st.label}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <Button size="sm" variant="outline" onClick={() => setSelected(a)} className="gap-1.5 h-8 text-[12px]">
                          <Eye className="h-3.5 w-3.5" /> Review & Vote
                        </Button>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
            )}
          </CardContent>
        </Card>
      )}

      <Dialog open={!!selected} onOpenChange={(o) => !o && setSelected(null)}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2"><Gavel className="h-5 w-5 text-primary" /> {selected?.title || "ARC Application"}</DialogTitle>
            <DialogDescription>
              Review the application details and cast your vote. Comments are visible to staff and committee members.
            </DialogDescription>
          </DialogHeader>
          {selected && (
            <div className="space-y-5">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div><p className="text-muted-foreground text-xs uppercase tracking-wide">Owner</p><p className="font-medium">{ownerName(selected)}</p></div>
                <div><p className="text-muted-foreground text-xs uppercase tracking-wide">Property</p><p className="font-medium">{propertyAddr(selected)}</p></div>
                <div><p className="text-muted-foreground text-xs uppercase tracking-wide">Association</p><p className="font-medium">{selected.associations?.name || "—"}</p></div>
                <div><p className="text-muted-foreground text-xs uppercase tracking-wide">Project Type</p><p className="font-medium">{selected.project_type || "—"}</p></div>
                <div><p className="text-muted-foreground text-xs uppercase tracking-wide">Submitted</p><p className="font-medium">{selected.submitted_date ? format(new Date(selected.submitted_date), "MMM d, yyyy") : selected.created_at ? format(new Date(selected.created_at), "MMM d, yyyy") : "—"}</p></div>
                <div><p className="text-muted-foreground text-xs uppercase tracking-wide">Status</p><p className="font-medium">{getStatus(selected.status).label}</p></div>
              </div>
              {selected.description && (
                <div>
                  <p className="text-muted-foreground text-xs uppercase tracking-wide mb-1">Description</p>
                  <p className="bg-muted p-3 rounded-md border whitespace-pre-wrap text-sm">{selected.description}</p>
                </div>
              )}
              {selected.decision_notes && (
                <div>
                  <p className="text-muted-foreground text-xs uppercase tracking-wide mb-1">Decision Notes</p>
                  <p className="bg-muted p-3 rounded-md border whitespace-pre-wrap text-sm">{selected.decision_notes}</p>
                </div>
              )}
              <VotingAndComments
                entityType="arc_application"
                entityId={selected.id}
                locked={["approved", "denied"].includes((selected.status || "").toLowerCase())}
                lockedMessage="This application has been finalized. Voting and comments are closed."
                showOwnerVisibilityToggle
              />
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}