import { useState, useEffect } from "react";
import { BellRing, Send, Search, FileText, ExternalLink, Share2, Copy, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import NotifyOwnersDialog from "@/components/NotifyOwnersDialog";
import { NotifyOwnersProvider, useNotifyOwners } from "@/contexts/NotifyOwnersContext";

// Send Proof Dialog
function SendProofDialog({ open, onOpenChange, proofRecord }: { open: boolean; onOpenChange: (v: boolean) => void; proofRecord: any }) {
  const { sendProofEmail } = useNotifyOwners();
  const { toast } = useToast();
  const [recipientInput, setRecipientInput] = useState("");
  const [senderId, setSenderId] = useState("");
  const [senders, setSenders] = useState<any[]>([]);
  const [sending, setSending] = useState(false);

  useEffect(() => {
    if (open) {
      setRecipientInput("");
      fetchSenders();
    }
  }, [open]);

  const fetchSenders = async () => {
    const { data: result } = await supabase.functions.invoke("send-smtp-email", {
      body: { action: "list_senders" },
    });
    const available = result?.senders || [];
    setSenders(available);
    if (available.length > 0) setSenderId(available[0].id);
  };

  const handleSend = async () => {
    const emails = recipientInput.split(",").map((e: string) => e.trim()).filter(Boolean);
    if (emails.length === 0 || !senderId) {
      toast({ variant: "destructive", title: "Error", description: "Enter at least one recipient email and select a sender." });
      return;
    }
    setSending(true);
    const result = await sendProofEmail({ proofRecord, senderId, recipientEmails: emails });
    setSending(false);
    if (result?.success) {
      toast({ title: "Proof Accepted", description: `Verification proof was accepted by the mail server for ${emails.length} recipient(s).` });
      onOpenChange(false);
    } else {
      toast({ variant: "destructive", title: "Failed", description: result?.error || "Failed to send proof." });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Send Verification Proof</DialogTitle>
          <DialogDescription>Forward this notification proof document to recipients via email.</DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="bg-muted rounded-md p-3 space-y-1">
            <p className="text-sm font-medium">{proofRecord?.subject}</p>
            <p className="text-xs text-muted-foreground">{proofRecord?.delivery_status}</p>
            <p className="text-xs font-mono text-muted-foreground">ID: {proofRecord?.validation_id?.substring(0, 12)}...</p>
          </div>
          <div className="space-y-2">
            <Label>From Sender</Label>
            <Select value={senderId} onValueChange={setSenderId}>
              <SelectTrigger><SelectValue placeholder="Select Sender" /></SelectTrigger>
              <SelectContent>
                {senders.map((s: any) => (
                  <SelectItem key={s.id} value={s.id}>{s.sender_name} ({s.email_address})</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label>Recipient Email(s)</Label>
            <Input
              placeholder="attorney@lawfirm.com, board@example.com"
              value={recipientInput}
              onChange={(e) => setRecipientInput(e.target.value)}
            />
            <p className="text-xs text-muted-foreground">Separate multiple emails with commas</p>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleSend} disabled={sending || !recipientInput.trim() || !senderId}>
            {sending ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Send className="w-4 h-4 mr-2" />}
            {sending ? "Sending..." : "Send Proof"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function NotifyOwnersPageContent() {
  const { user } = useAuth();
  const { toast } = useToast();
  const { setSelectedClientId, getOwnersByConsent } = useNotifyOwners();
  const [associations, setAssociations] = useState<any[]>([]);
  const [selectedAssocId, setSelectedAssocId] = useState("");
  const [ownerStats, setOwnerStats] = useState({ total: 0, consented: 0 });
  const [history, setHistory] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [showCompose, setShowCompose] = useState(false);
  const [proofToSend, setProofToSend] = useState<any>(null);
  const [showSendProof, setShowSendProof] = useState(false);

  useEffect(() => { fetchAssociations(); }, []);
  useEffect(() => { if (selectedAssocId) { fetchOwnerStats(); fetchHistory(); setSelectedClientId(selectedAssocId); } }, [selectedAssocId]);

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

  const fetchOwnerStats = async () => {
    const { data: owners } = await supabase.from("owners").select("id, email, electronic_consent").eq("status", "active").eq("association_id", selectedAssocId);
    if (owners) {
      const withEmail = owners.filter((o: any) => o.email);
      const consented = owners.filter((o: any) => o.electronic_consent && o.email);
      setOwnerStats({ total: withEmail.length, consented: consented.length });
    }
  };

  const fetchHistory = async () => {
    const { data } = await supabase.from("owner_notification_proofs").select("*").eq("association_id", selectedAssocId).order("created_at", { ascending: false });
    setHistory(data || []);
  };

  const copyProofLink = (url: string) => {
    navigator.clipboard.writeText(url);
    toast({ title: "Copied", description: "Proof link copied to clipboard." });
  };

  const handleSendProof = (record: any) => {
    setProofToSend(record);
    setShowSendProof(true);
  };

  const filteredHistory = history.filter((h: any) => !searchTerm || (h.subject || "").toLowerCase().includes(searchTerm.toLowerCase()));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <BellRing className="h-7 w-7 text-primary" />
          <div>
            <h1 className="text-2xl font-bold text-foreground">Notify Owners</h1>
            <p className="text-sm text-muted-foreground">Send email blasts and notifications to property owners with cryptographic proofs.</p>
          </div>
        </div>
        <Select value={selectedAssocId} onValueChange={setSelectedAssocId}>
          <SelectTrigger className="w-[300px]"><SelectValue /></SelectTrigger>
          <SelectContent>
            {associations.map((a) => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
          </SelectContent>
        </Select>
      </div>

      <Tabs defaultValue="send">
        <TabsList>
          <TabsTrigger value="send" className="gap-2"><Send className="h-4 w-4" /> Send Notification</TabsTrigger>
          <TabsTrigger value="history" className="gap-2"><FileText className="h-4 w-4" /> History & Proofs</TabsTrigger>
        </TabsList>

        <TabsContent value="send" className="mt-6 space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Card>
              <CardContent className="pt-6">
                <p className="text-xs font-semibold text-muted-foreground uppercase">Total Owners (w/ Email)</p>
                <p className="text-3xl font-bold text-foreground mt-1">{ownerStats.total}</p>
                <p className="text-xs text-muted-foreground mt-1">Available for generic blasts</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6">
                <p className="text-xs font-semibold text-muted-foreground uppercase">Consented Owners</p>
                <p className="text-3xl font-bold text-foreground mt-1">{ownerStats.consented}</p>
                <p className="text-xs text-muted-foreground mt-1">Opted-in for electronic notices</p>
              </CardContent>
            </Card>
            <Card className="flex items-center justify-center">
              <CardContent className="pt-6">
                <Button size="lg" onClick={() => setShowCompose(true)} className="gap-2">
                  <Send className="h-5 w-5" /> Compose Notification
                </Button>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="history" className="mt-6">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="flex items-center gap-2"><FileText className="h-5 w-5" /> Notification History & Proofs</CardTitle>
                  <CardDescription>Recent email blasts with delivery status and verification proofs.</CardDescription>
                </div>
                <Input placeholder="Search subjects..." className="max-w-xs" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
              </div>
            </CardHeader>
            <CardContent>
              {filteredHistory.length === 0 ? (
                <p className="text-center text-muted-foreground py-8">No notification history yet.</p>
              ) : (
                <div className="space-y-4">
                  {filteredHistory.map((h: any) => {
                    const ownersNotified = Array.isArray(h.owners_notified) ? h.owners_notified : [];
                    const sentCount = ownersNotified.filter((o: any) => o.status === 'sent').length;
                    const failedCount = ownersNotified.filter((o: any) => o.status === 'failed').length;

                    return (
                      <div key={h.id} className="border rounded-lg p-4 space-y-3">
                        <div className="flex items-start justify-between">
                          <div className="flex-1">
                            <h3 className="font-semibold">{h.subject}</h3>
                            <p className="text-sm text-muted-foreground line-clamp-2 mt-1">{h.body?.replace(/<[^>]*>/g, '').substring(0, 120)}</p>
                          </div>
                        </div>
                        
                        <div className="flex flex-wrap gap-2 text-xs">
                          <span className="text-muted-foreground">{new Date(h.created_at).toLocaleString()}</span>
                          {sentCount > 0 && <Badge variant="secondary" className="bg-emerald-100 text-emerald-700">✓ {sentCount} Sent</Badge>}
                          {failedCount > 0 && <Badge variant="secondary" className="bg-red-100 text-red-700">✗ {failedCount} Failed</Badge>}
                          {h.validation_id && <span className="font-mono text-muted-foreground">ID: {h.validation_id?.substring(0, 10)}...</span>}
                        </div>

                        <div className="flex gap-2 pt-1">
                          {h.proof_url && (
                            <>
                              <Button variant="outline" size="sm" onClick={() => window.open(h.proof_url, "_blank")}>
                                <ExternalLink className="h-3.5 w-3.5 mr-1" /> View Proof
                              </Button>
                              <Button variant="outline" size="sm" onClick={() => copyProofLink(h.proof_url)}>
                                <Copy className="h-3.5 w-3.5 mr-1" /> Copy Link
                              </Button>
                            </>
                          )}
                          <Button variant="outline" size="sm" onClick={() => handleSendProof(h)}>
                            <Share2 className="h-3.5 w-3.5 mr-1" /> Send Proof
                          </Button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      <NotifyOwnersDialog open={showCompose} onOpenChange={setShowCompose} />
      <SendProofDialog open={showSendProof} onOpenChange={setShowSendProof} proofRecord={proofToSend} />
    </div>
  );
}

export default function NotifyOwnersPage() {
  return (
    <NotifyOwnersProvider>
      <NotifyOwnersPageContent />
    </NotifyOwnersProvider>
  );
}
