import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import { Plus, Building2, Search, MapPin, Phone, Mail, Archive } from "lucide-react";
import { Switch } from "@/components/ui/switch";
import type { Tables } from "@/integrations/supabase/types";

export default function AssociationsPage() {
  const navigate = useNavigate();
  const [associations, setAssociations] = useState<Tables<"associations">[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState(() => localStorage.getItem("assoc_dir_search") || "");
  const [showArchived, setShowArchived] = useState(() => localStorage.getItem("assoc_dir_archived") === "true");
  const lastViewedId = localStorage.getItem("assoc_dir_last_viewed");
  const [dialogOpen, setDialogOpen] = useState(false);
  const { toast } = useToast();

  const fetchAssociations = async () => {
    const { data, error } = await supabase.from("associations").select("*").order("name");
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      setAssociations(data || []);
    }
    setLoading(false);
  };

  useEffect(() => { fetchAssociations(); }, []);

  useEffect(() => { localStorage.setItem("assoc_dir_search", search); }, [search]);
  useEffect(() => { localStorage.setItem("assoc_dir_archived", String(showArchived)); }, [showArchived]);

  useEffect(() => {
    if (!loading && lastViewedId) {
      const el = document.getElementById(`assoc-card-${lastViewedId}`);
      if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  }, [loading, lastViewedId]);

  const handleCreate = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = new FormData(e.currentTarget);
    const { error } = await supabase.from("associations").insert({
      name: form.get("name") as string,
      address: form.get("address") as string,
      city: form.get("city") as string,
      state: form.get("state") as string,
      zip: form.get("zip") as string,
      phone: form.get("phone") as string,
      email: form.get("email") as string,
    });
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Association created" });
      setDialogOpen(false);
      fetchAssociations();
    }
  };

  const filtered = associations.filter((a) => {
    const matchesSearch = a.name.toLowerCase().includes(search.toLowerCase());
    const status = (a as any).status || "active";
    const matchesStatus = showArchived ? status === "archived" : status !== "archived";
    return matchesSearch && matchesStatus;
  });

  const archivedCount = associations.filter(a => (a as any).status === "archived").length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Associations</h1>
          <p className="text-sm text-muted-foreground">Manage your HOA communities</p>
        </div>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button className="gap-2"><Plus className="h-4 w-4" />Add Association</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>New Association</DialogTitle></DialogHeader>
            <form onSubmit={handleCreate} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="name">Name *</Label>
                <Input id="name" name="name" required />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2"><Label htmlFor="address">Address</Label><Input id="address" name="address" /></div>
                <div className="space-y-2"><Label htmlFor="city">City</Label><Input id="city" name="city" /></div>
                <div className="space-y-2"><Label htmlFor="state">State</Label><Input id="state" name="state" /></div>
                <div className="space-y-2"><Label htmlFor="zip">ZIP</Label><Input id="zip" name="zip" /></div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2"><Label htmlFor="phone">Phone</Label><Input id="phone" name="phone" /></div>
                <div className="space-y-2"><Label htmlFor="email">Email</Label><Input id="email" name="email" type="email" /></div>
              </div>
              <Button type="submit" className="w-full">Create Association</Button>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      <div className="flex items-center gap-4">
        <div className="relative max-w-sm flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input placeholder="Search associations..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-10" />
        </div>
        {archivedCount > 0 && (
          <div className="flex items-center gap-2">
            <Switch checked={showArchived} onCheckedChange={setShowArchived} id="show-archived" />
            <Label htmlFor="show-archived" className="text-sm text-muted-foreground flex items-center gap-1 cursor-pointer">
              <Archive className="h-3.5 w-3.5" /> Archived ({archivedCount})
            </Label>
          </div>
        )}
      </div>
      {showArchived && (
        <div className="flex items-center gap-3 rounded-lg border border-border bg-muted/50 px-4 py-3">
          <Archive className="h-4 w-4 text-muted-foreground shrink-0" />
          <span className="text-sm text-muted-foreground">Viewing archived associations</span>
          <Button variant="outline" size="sm" className="ml-auto gap-1.5" onClick={() => setShowArchived(false)}>
            <Building2 className="h-3.5 w-3.5" /> Show Active Associations
          </Button>
        </div>
      )}

      {loading ? (
        <div className="flex justify-center py-12"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">
          <Building2 className="mx-auto h-12 w-12 mb-4 opacity-50" />
          <p>{search ? "No associations match your search." : showArchived ? "No archived associations." : "No associations yet. Create your first one!"}</p>
          {showArchived && (
            <Button variant="link" className="mt-2" onClick={() => setShowArchived(false)}>
              ← Back to active associations
            </Button>
          )}
        </CardContent></Card>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filtered.map((assoc) => (
            <Card id={`assoc-card-${assoc.id}`} key={assoc.id} className={`hover:shadow-md transition-shadow cursor-pointer ${(assoc as any).status === "archived" ? "opacity-60" : ""} ${assoc.id === lastViewedId ? "ring-2 ring-primary/40" : ""}`} onClick={() => { localStorage.setItem("assoc_dir_last_viewed", assoc.id); navigate(`/dashboard/associations/${assoc.id}`); }}>
              <CardHeader className="pb-3">
                <CardTitle className="flex items-center gap-2 text-lg">
                  <Building2 className="h-5 w-5 text-primary" />
                  {assoc.name}
                  {(assoc as any).status === "archived" && <Badge variant="secondary" className="ml-auto text-xs">Archived</Badge>}
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-2 text-sm">
                {assoc.address && (
                  <div className="flex items-center gap-2 text-muted-foreground">
                    <MapPin className="h-3.5 w-3.5" />
                    {assoc.address}{assoc.city && `, ${assoc.city}`}{assoc.state && `, ${assoc.state}`} {assoc.zip}
                  </div>
                )}
                {assoc.phone && (
                  <div className="flex items-center gap-2 text-muted-foreground">
                    <Phone className="h-3.5 w-3.5" />{assoc.phone}
                  </div>
                )}
                {assoc.email && (
                  <div className="flex items-center gap-2 text-muted-foreground">
                    <Mail className="h-3.5 w-3.5" />{assoc.email}
                  </div>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}