import { useState, useEffect, useMemo } from "react";
import { AtSign, Plus, Pencil, Trash2, RefreshCw, Send, Wifi, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import ReactQuill from "react-quill-new";
import "react-quill-new/dist/quill.snow.css";

const emptyForm = { sender_name: "", email_address: "", smtp_host: "", smtp_port: 465, smtp_username: "", smtp_password: "", use_tls: true, use_ssl: false, is_default: false, signature_html: "" };

export default function EmailSendersPage() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [senders, setSenders] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [showDialog, setShowDialog] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);
  const [form, setForm] = useState(emptyForm);

  const quillModules = useMemo(() => ({
    toolbar: [["bold", "italic", "underline"], [{ list: "ordered" }, { list: "bullet" }], ["link", "image"], ["clean"]],
  }), []);

  // Test email state
  const [testingSenderId, setTestingSenderId] = useState<string | null>(null);
  const [testingConnectionId, setTestingConnectionId] = useState<string | null>(null);
  const [showTestEmail, setShowTestEmail] = useState(false);
  const [testSender, setTestSender] = useState<any>(null);
  const [testRecipient, setTestRecipient] = useState("");

  useEffect(() => { if (user) fetchSenders(); }, [user]);

  const fetchSenders = async () => {
    setLoading(true);
    const { data } = await supabase.from("email_senders").select("*").order("is_default", { ascending: false });
    setSenders(data || []);
    setLoading(false);
  };

  const openNew = () => { setEditId(null); setForm(emptyForm); setShowDialog(true); };
  const openEdit = (s: any) => {
    setEditId(s.id);
    setForm({ sender_name: s.sender_name, email_address: s.email_address, smtp_host: s.smtp_host || "", smtp_port: s.smtp_port || 465, smtp_username: s.smtp_username || "", smtp_password: s.smtp_password || "", use_tls: s.use_tls, use_ssl: s.use_ssl, is_default: s.is_default, signature_html: s.signature_html || "" });
    setShowDialog(true);
  };

  const handleSave = async () => {
    if (!form.sender_name || !form.email_address) {
      toast({ variant: "destructive", title: "Error", description: "Name and email required." }); return;
    }
    if (!form.smtp_host || !form.smtp_username || !form.smtp_password) {
      toast({ variant: "destructive", title: "Error", description: "SMTP host, username, and password are required." }); return;
    }

    const normalizedEmail = form.email_address.trim().toLowerCase();
    const normalizedUsername = form.smtp_username.trim().toLowerCase();

    const { data: existingSenders, error: existingError } = await supabase
      .from("email_senders")
      .select("id, email_address, smtp_username")
      .eq("user_id", user?.id);

    if (existingError) {
      toast({ variant: "destructive", title: "Error", description: existingError.message }); return;
    }

    const matchingSender = (existingSenders || []).find((sender) =>
      sender.id !== editId &&
      (sender.email_address || "").trim().toLowerCase() === normalizedEmail &&
      (sender.smtp_username || "").trim().toLowerCase() === normalizedUsername
    );

    const payload = { ...form, user_id: user?.id, is_active: true, verified: false };
    if (editId) {
      const { error } = await supabase.from("email_senders").update(payload).eq("id", editId);
      if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); return; }
    } else if (matchingSender) {
      const { error } = await supabase.from("email_senders").update(payload).eq("id", matchingSender.id);
      if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); return; }
    } else {
      const { error } = await supabase.from("email_senders").insert(payload);
      if (error) { toast({ variant: "destructive", title: "Error", description: error.message }); return; }
    }
    toast({ title: "Saved", description: matchingSender && !editId ? "Existing sender updated with the new credentials." : "Sender configuration saved." });
    setShowDialog(false); fetchSenders();
  };

  const handleDelete = async (id: string) => {
    await supabase.from("email_senders").delete().eq("id", id);
    toast({ title: "Deleted" }); fetchSenders();
  };

  const handleTestConnection = async (sender: any) => {
    setTestingConnectionId(sender.id);
    try {
      const { data, error } = await supabase.functions.invoke("test-smtp-connection", {
        body: {
          action: "test_connection",
          smtp_host: sender.smtp_host,
          smtp_port: sender.smtp_port,
          smtp_username: sender.smtp_username,
          smtp_password: sender.smtp_password,
        },
      });
      if (error) throw error;
      if (data?.success) {
        toast({ title: "Connection Successful", description: data.message || "SMTP server is reachable." });
      } else {
        toast({ variant: "destructive", title: "Connection Failed", description: data?.error || "Could not connect." });
      }
    } catch (err: any) {
      toast({ variant: "destructive", title: "Error", description: err.message });
    } finally {
      setTestingConnectionId(null);
    }
  };

  const openTestEmail = (sender: any) => {
    setTestSender(sender);
    setTestRecipient("");
    setShowTestEmail(true);
  };

  const handleSendTestEmail = async () => {
    if (!testSender) return;
    setTestingSenderId(testSender.id);
    try {
      const { data, error } = await supabase.functions.invoke("test-smtp-connection", {
        body: {
          action: "send_test_email",
          smtp_host: testSender.smtp_host,
          smtp_port: testSender.smtp_port,
          smtp_username: testSender.smtp_username,
          smtp_password: testSender.smtp_password,
          test_recipient: testRecipient || undefined,
        },
      });
      if (error) throw error;
      if (data?.success) {
        toast({ title: "Test Email Sent", description: data.message || "Check your inbox." });
        setShowTestEmail(false);
      } else {
        toast({ variant: "destructive", title: "Send Failed", description: data?.error || "Failed to send." });
      }
    } catch (err: any) {
      toast({ variant: "destructive", title: "Error", description: err.message });
    } finally {
      setTestingSenderId(null);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <AtSign className="h-7 w-7 text-primary" />
          <div>
            <h1 className="text-2xl font-bold text-foreground">Email Senders</h1>
            <p className="text-sm text-muted-foreground">Configure your SMTP email sender accounts. Each sender includes its own SMTP credentials.</p>
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="icon" onClick={fetchSenders}><RefreshCw className="h-4 w-4" /></Button>
          <Button onClick={openNew}><Plus className="h-4 w-4 mr-2" /> Add New Sender</Button>
        </div>
      </div>

      <Card>
        <CardHeader><CardTitle>Configured Senders</CardTitle><CardDescription>All email sending uses these sender configurations.</CardDescription></CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Sender Name</TableHead>
                <TableHead>Email Address</TableHead>
                <TableHead>SMTP Host</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {senders.length === 0 ? (
                <TableRow><TableCell colSpan={5} className="text-center py-12 text-muted-foreground">No senders configured yet. Add one to start sending emails.</TableCell></TableRow>
              ) : (
                senders.map((s) => (
                  <TableRow key={s.id}>
                    <TableCell className="font-medium">
                      {s.sender_name}
                      {s.is_default && <Badge className="ml-2 bg-primary/10 text-primary" variant="secondary">Default</Badge>}
                    </TableCell>
                    <TableCell>{s.email_address}</TableCell>
                    <TableCell className="font-mono text-sm">{s.smtp_host ? `${s.smtp_host}:${s.smtp_port}` : "—"}</TableCell>
                    <TableCell>
                      <div className="flex flex-col items-start gap-1">
                        <Badge className={s.is_active ? "bg-emerald-100 text-emerald-700" : "bg-muted text-muted-foreground"} variant="secondary">{s.is_active ? "Active" : "Inactive"}</Badge>
                        {s.verified && <span className="text-xs text-emerald-600">✓ Verified</span>}
                      </div>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Button
                          variant="ghost" size="icon" title="Test Connection"
                          onClick={() => handleTestConnection(s)}
                          disabled={!s.smtp_host || testingConnectionId === s.id}
                        >
                          {testingConnectionId === s.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Wifi className="h-4 w-4" />}
                        </Button>
                        <Button
                          variant="ghost" size="icon" title="Send Test Email"
                          onClick={() => openTestEmail(s)}
                          disabled={!s.smtp_host}
                        >
                          <Send className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => openEdit(s)}><Pencil className="h-4 w-4" /></Button>
                        <Button variant="ghost" size="icon" className="text-destructive" onClick={() => handleDelete(s.id)}><Trash2 className="h-4 w-4" /></Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Add/Edit Sender Dialog */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editId ? "Edit Sender" : "Add New Sender"}</DialogTitle>
            <DialogDescription>Configure the sender identity and SMTP credentials.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>Sender Name</Label><Input value={form.sender_name} onChange={(e) => setForm({ ...form, sender_name: e.target.value })} placeholder="e.g. ACM Mail" /></div>
              <div className="space-y-2"><Label>Email Address</Label><Input value={form.email_address} onChange={(e) => setForm({ ...form, email_address: e.target.value })} placeholder="mail@example.com" /></div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>SMTP Host</Label><Input value={form.smtp_host} onChange={(e) => setForm({ ...form, smtp_host: e.target.value })} placeholder="smtp.example.com" /></div>
              <div className="space-y-2"><Label>SMTP Port</Label><Input type="number" value={form.smtp_port} onChange={(e) => setForm({ ...form, smtp_port: Number(e.target.value) })} /></div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>Username</Label><Input value={form.smtp_username} onChange={(e) => setForm({ ...form, smtp_username: e.target.value })} placeholder="Usually your email address" /></div>
              <div className="space-y-2"><Label>Password</Label><Input type="password" value={form.smtp_password} onChange={(e) => setForm({ ...form, smtp_password: e.target.value })} /></div>
            </div>
            <div className="flex items-center gap-6">
              <div className="flex items-center gap-2"><Switch checked={form.use_tls} onCheckedChange={(v) => setForm({ ...form, use_tls: v })} /><Label>Use TLS</Label></div>
              <div className="flex items-center gap-2"><Switch checked={form.is_default} onCheckedChange={(v) => setForm({ ...form, is_default: v })} /><Label>Default</Label></div>
            </div>
            <div className="space-y-2">
              <Label>Email Signature</Label>
              <p className="text-xs text-muted-foreground">This signature will be appended to all outgoing emails from this sender.</p>
              <ReactQuill
                theme="snow"
                value={form.signature_html}
                onChange={(v) => setForm({ ...form, signature_html: v })}
                modules={quillModules}
                placeholder="e.g. Best regards, Your Name | Company"
                className="[&_.ql-editor]:min-h-[80px]"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>Cancel</Button>
            <Button onClick={handleSave}>Save Sender</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Send Test Email Dialog */}
      <Dialog open={showTestEmail} onOpenChange={setShowTestEmail}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Send Test Email</DialogTitle>
            <DialogDescription>Verify this sender's SMTP configuration is working.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Recipient Email</Label>
              <Input
                type="email"
                placeholder="Leave blank to send to your login email"
                value={testRecipient}
                onChange={(e) => setTestRecipient(e.target.value)}
              />
              <p className="text-xs text-muted-foreground">If left blank, the test email will be sent to your account email.</p>
            </div>
            {testSender && (
              <div className="rounded-md bg-muted p-3 text-sm">
                <p className="font-medium mb-1">Sending From</p>
                <p className="text-muted-foreground">{testSender.sender_name} &lt;{testSender.email_address}&gt;</p>
                <p className="text-muted-foreground font-mono text-xs">{testSender.smtp_host}:{testSender.smtp_port}</p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowTestEmail(false)}>Cancel</Button>
            <Button onClick={handleSendTestEmail} disabled={testingSenderId === testSender?.id}>
              {testingSenderId === testSender?.id ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Send className="h-4 w-4 mr-2" />}
              {testingSenderId === testSender?.id ? "Sending..." : "Send Test"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
