import { useState, useEffect } from "react";
import { formatDateEST } from "@/lib/timezoneUtils";
import { MailOpen, Plus, Trash2, Search, Copy } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";

export default function EmailRoutingPage() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState<any[]>([]);
  const [selectedAssociation, setSelectedAssociation] = useState<any>(null);
  const [rules, setRules] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [newEmail, setNewEmail] = useState("");

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

  useEffect(() => {
    if (selectedAssociation) fetchRules(selectedAssociation.id);
  }, [selectedAssociation]);

  const fetchAssociations = async () => {
    const { data } = await supabase.from("associations").select("id, name").eq("status", "active").order("name");
    setAssociations(data || []);
  };

  const fetchRules = async (assocId: string) => {
    const { data } = await supabase.from("email_routing_rules").select("*").eq("association_id", assocId).order("created_at", { ascending: false });
    setRules(data || []);
  };

  const handleAddRule = async () => {
    if (!newEmail.trim() || !selectedAssociation) return;
    const { error } = await supabase.from("email_routing_rules").insert({ association_id: selectedAssociation.id, email_address: newEmail.trim() });
    if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); return; }
    toast({ title: "Added", description: "Email routing rule added." });
    setNewEmail(""); setShowAddDialog(false);
    fetchRules(selectedAssociation.id);
  };

  const handleDelete = async (id: string) => {
    await supabase.from("email_routing_rules").delete().eq("id", id);
    toast({ title: "Deleted", description: "Routing rule removed." });
    if (selectedAssociation) fetchRules(selectedAssociation.id);
  };

  const filtered = associations.filter((a) => a.name.toLowerCase().includes(searchTerm.toLowerCase()));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <MailOpen className="h-7 w-7 text-primary" />
          <div>
            <h1 className="text-2xl font-bold text-foreground">Email Routing</h1>
            <p className="text-sm text-muted-foreground">Manage inbound email addresses assigned to each association.</p>
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="icon"><Copy className="h-4 w-4" /></Button>
          <Button onClick={() => setShowAddDialog(true)} disabled={!selectedAssociation}>
            <Plus className="h-4 w-4 mr-2" /> Add Email Rule
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="lg:col-span-1">
          <CardContent className="p-4 space-y-3">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input placeholder="Search clients..." className="pl-9" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
            </div>
            <div className="space-y-1 max-h-[600px] overflow-y-auto">
              {filtered.map((a) => (
                <button key={a.id}
                  className={`w-full text-left px-3 py-2.5 rounded-lg text-sm transition-colors flex items-center gap-2 ${selectedAssociation?.id === a.id ? "bg-primary/10 text-primary font-medium" : "hover:bg-muted text-foreground"}`}
                  onClick={() => setSelectedAssociation(a)}>
                  <span className="truncate">{a.name}</span>
                </button>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card className="lg:col-span-2">
          <CardContent className="p-6">
            {selectedAssociation ? (
              <div className="space-y-4">
                <div>
                  <h2 className="text-lg font-semibold text-foreground">{selectedAssociation.name}</h2>
                  <p className="text-sm text-muted-foreground">Emails sent to these addresses will be routed to {selectedAssociation.name}...</p>
                </div>
                <div className="space-y-3">
                  {rules.length === 0 ? (
                    <p className="text-sm text-muted-foreground py-8 text-center">No routing rules configured for this association.</p>
                  ) : (
                    rules.map((rule) => (
                      <div key={rule.id} className="flex items-center justify-between p-3 border rounded-lg">
                        <div className="flex items-center gap-3">
                          <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center">
                            <MailOpen className="h-4 w-4 text-primary" />
                          </div>
                          <div>
                            <p className="font-medium text-sm">{rule.email_address}</p>
                            <p className="text-xs text-muted-foreground">Added {formatDateEST(rule.created_at)}</p>
                          </div>
                        </div>
                        <Button variant="ghost" size="icon" className="text-destructive hover:text-destructive" onClick={() => handleDelete(rule.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    ))
                  )}
                </div>
              </div>
            ) : (
              <p className="text-center text-muted-foreground py-16">Select an association to manage email routing rules.</p>
            )}
          </CardContent>
        </Card>
      </div>

      <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
        <DialogContent>
          <DialogHeader><DialogTitle>Add Email Routing Rule</DialogTitle></DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Email Address</Label>
              <Input placeholder="email@example.com" value={newEmail} onChange={(e) => setNewEmail(e.target.value)} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAddDialog(false)}>Cancel</Button>
            <Button onClick={handleAddRule}>Add Rule</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
