import React, { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Loader2, Mail, RefreshCw, CheckCircle2, AlertCircle, Plus, Send, ExternalLink } from "lucide-react";
import { Textarea } from "@/components/ui/textarea";
import { format } from "date-fns";

interface Association { id: string; name: string; }
interface MailchimpConfig {
  id: string;
  association_id: string;
  api_key: string;
  server_prefix: string;
  audience_id: string | null;
  audience_name: string | null;
  last_sync_at: string | null;
  last_sync_status: string | null;
  last_sync_count: number | null;
  last_sync_error: string | null;
}
interface Audience { id: string; name: string; stats?: { member_count?: number } }

export default function MailchimpPage() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState<Association[]>([]);
  const [selectedAssoc, setSelectedAssoc] = useState<string>("");
  const [config, setConfig] = useState<MailchimpConfig | null>(null);
  const [loading, setLoading] = useState(false);
  const [syncing, setSyncing] = useState(false);

  // Form state
  const [apiKey, setApiKey] = useState("");
  const [serverPrefix, setServerPrefix] = useState("");
  const [audiences, setAudiences] = useState<Audience[]>([]);
  const [selectedAudience, setSelectedAudience] = useState<string>("");
  const [newAudienceName, setNewAudienceName] = useState("");
  const [showCreate, setShowCreate] = useState(false);
  const [ownerCount, setOwnerCount] = useState<number>(0);

  // Campaign state
  const [campaignSubject, setCampaignSubject] = useState("");
  const [campaignFromName, setCampaignFromName] = useState("");
  const [campaignReplyTo, setCampaignReplyTo] = useState("");
  const [campaignHtml, setCampaignHtml] = useState("");
  const [sendingCampaign, setSendingCampaign] = useState(false);
  const [lastCampaign, setLastCampaign] = useState<{ web_id?: number; sent: boolean } | null>(null);

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

  useEffect(() => {
    if (!selectedAssoc) return;
    loadConfig(selectedAssoc);
    loadOwnerCount(selectedAssoc);
  }, [selectedAssoc]);

  const loadOwnerCount = async (id: string) => {
    const { count } = await supabase.from("owners").select("id", { count: "exact", head: true })
      .eq("association_id", id).eq("status", "active").not("email", "is", null);
    setOwnerCount(count || 0);
  };

  const loadConfig = async (id: string) => {
    setLoading(true);
    setConfig(null);
    setApiKey(""); setServerPrefix(""); setAudiences([]); setSelectedAudience(""); setShowCreate(false);
    try {
      const { data, error } = await supabase.from("mailchimp_configs").select("*").eq("association_id", id).maybeSingle();
      if (error) throw error;
      if (data) {
        setConfig(data as any);
        setApiKey(data.api_key);
        setServerPrefix(data.server_prefix);
        setSelectedAudience(data.audience_id || "");
      }
    } catch (e: any) {
      toast({ variant: "destructive", title: "Load error", description: e.message });
    } finally {
      setLoading(false);
    }
  };

  const detectPrefix = (key: string) => {
    const parts = key.split("-");
    return parts.length > 1 ? parts[parts.length - 1] : "";
  };

  const handleApiKeyChange = (val: string) => {
    setApiKey(val);
    if (!serverPrefix) {
      const detected = detectPrefix(val.trim());
      if (detected) setServerPrefix(detected);
    }
  };

  const handleTestAndLoad = async () => {
    if (!apiKey || !serverPrefix) {
      toast({ variant: "destructive", title: "Missing info", description: "Enter API key and server prefix." });
      return;
    }
    setLoading(true);
    try {
      const { data, error } = await supabase.functions.invoke("mailchimp-audiences", {
        body: { action: "list", api_key: apiKey, server_prefix: serverPrefix },
      });
      if (error) throw error;
      if (!data.success) throw new Error(data.error || "Failed to connect");
      setAudiences(data.lists || []);
      toast({ title: "Connected", description: `Found ${data.lists?.length || 0} audience(s).` });
    } catch (e: any) {
      toast({ variant: "destructive", title: "Mailchimp connection failed", description: e.message });
    } finally {
      setLoading(false);
    }
  };

  const handleCreateAudience = async () => {
    const assoc = associations.find(a => a.id === selectedAssoc);
    const name = newAudienceName.trim() || assoc?.name || "HOA Owners";
    setLoading(true);
    try {
      const { data, error } = await supabase.functions.invoke("mailchimp-audiences", {
        body: {
          action: "create",
          api_key: apiKey,
          server_prefix: serverPrefix,
          audience_name: name,
          association_name: assoc?.name,
        },
      });
      if (error) throw error;
      if (!data.success) throw new Error(data.error || "Create failed");
      toast({ title: "Audience created", description: data.list?.name });
      setSelectedAudience(data.list.id);
      await handleTestAndLoad();
      setShowCreate(false);
      setNewAudienceName("");
    } catch (e: any) {
      toast({ variant: "destructive", title: "Create failed", description: e.message });
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (!selectedAssoc || !apiKey || !serverPrefix) {
      toast({ variant: "destructive", title: "Missing fields", description: "API key, server prefix and audience are required." });
      return;
    }
    setLoading(true);
    try {
      const audience = audiences.find(a => a.id === selectedAudience);
      const { data: { user } } = await supabase.auth.getUser();
      const payload = {
        association_id: selectedAssoc,
        api_key: apiKey,
        server_prefix: serverPrefix,
        audience_id: selectedAudience || null,
        audience_name: audience?.name || null,
        created_by: user?.id,
      };
      const { error } = config
        ? await supabase.from("mailchimp_configs").update(payload).eq("id", config.id)
        : await supabase.from("mailchimp_configs").insert(payload);
      if (error) throw error;
      toast({ title: "Saved", description: "Mailchimp configuration updated." });
      loadConfig(selectedAssoc);
    } catch (e: any) {
      toast({ variant: "destructive", title: "Save failed", description: e.message });
    } finally {
      setLoading(false);
    }
  };

  const handleSync = async () => {
    if (!config?.audience_id) {
      toast({ variant: "destructive", title: "Not configured", description: "Save Mailchimp config with an audience first." });
      return;
    }
    setSyncing(true);
    try {
      const { data, error } = await supabase.functions.invoke("mailchimp-sync", {
        body: { association_id: selectedAssoc },
      });
      if (error) throw error;
      if (!data.success) throw new Error(data.error || "Sync failed");
      toast({
        title: "Sync complete",
        description: `${data.succeeded} synced${data.failed > 0 ? `, ${data.failed} failed` : ""}.`,
      });
      loadConfig(selectedAssoc);
    } catch (e: any) {
      toast({ variant: "destructive", title: "Sync failed", description: e.message });
    } finally {
      setSyncing(false);
    }
  };

  const handleDisconnect = async () => {
    if (!config) return;
    if (!confirm("Disconnect Mailchimp for this association? Owners already in Mailchimp won't be removed.")) return;
    setLoading(true);
    try {
      const { error } = await supabase.from("mailchimp_configs").delete().eq("id", config.id);
      if (error) throw error;
      toast({ title: "Disconnected" });
      loadConfig(selectedAssoc);
    } catch (e: any) {
      toast({ variant: "destructive", title: "Failed", description: e.message });
    } finally {
      setLoading(false);
    }
  };

  const handleSendCampaign = async (sendNow: boolean) => {
    if (!campaignSubject || !campaignFromName || !campaignReplyTo || !campaignHtml) {
      toast({ variant: "destructive", title: "Missing fields", description: "Subject, from name, reply-to and content are required." });
      return;
    }
    setSendingCampaign(true);
    setLastCampaign(null);
    try {
      const { data, error } = await supabase.functions.invoke("mailchimp-campaign", {
        body: {
          association_id: selectedAssoc,
          subject: campaignSubject,
          from_name: campaignFromName,
          reply_to: campaignReplyTo,
          html: campaignHtml,
          send_now: sendNow,
        },
      });
      if (error) throw error;
      if (!data.success) throw new Error(data.error || "Campaign failed");
      setLastCampaign({ web_id: data.web_id, sent: data.sent });
      toast({
        title: sendNow ? "Campaign sent!" : "Draft created",
        description: sendNow
          ? "Mailchimp is delivering your campaign to the audience."
          : "Saved as a draft in Mailchimp — review and send from there.",
      });
      if (sendNow) {
        setCampaignSubject(""); setCampaignHtml("");
      }
    } catch (e: any) {
      toast({ variant: "destructive", title: "Campaign failed", description: e.message });
    } finally {
      setSendingCampaign(false);
    }
  };

  return (
    <div className="container mx-auto p-6 max-w-4xl space-y-6">
      <div className="flex items-center gap-3">
        <Mail className="w-7 h-7 text-primary" />
        <div>
          <h1 className="text-2xl font-bold text-foreground">Mailchimp Integration</h1>
          <p className="text-sm text-muted-foreground">Sync owners from each association into a Mailchimp audience for marketing campaigns.</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Select Association</CardTitle>
          <CardDescription>Each association uses its own Mailchimp account and audience.</CardDescription>
        </CardHeader>
        <CardContent>
          <Select value={selectedAssoc} onValueChange={setSelectedAssoc}>
            <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
            <SelectContent>
              {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
            </SelectContent>
          </Select>
          {selectedAssoc && (
            <p className="text-sm text-muted-foreground mt-3">
              <span className="font-medium text-foreground">{ownerCount}</span> active owner(s) with email in this association.
            </p>
          )}
        </CardContent>
      </Card>

      {selectedAssoc && (
        <Card>
          <CardHeader className="flex flex-row items-start justify-between">
            <div>
              <CardTitle>Mailchimp Credentials</CardTitle>
              <CardDescription>
                Get your API key from Mailchimp → Account → Extras → API keys. The server prefix is the suffix after the dash (e.g. <code className="bg-muted px-1 rounded">us21</code>).
              </CardDescription>
            </div>
            {config && (
              <Badge variant="outline" className="bg-green-500/10 text-green-700 border-green-500/30">
                <CheckCircle2 className="w-3 h-3 mr-1" /> Connected
              </Badge>
            )}
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid md:grid-cols-2 gap-4">
              <div>
                <Label>API Key</Label>
                <Input
                  type="password"
                  value={apiKey}
                  onChange={(e) => handleApiKeyChange(e.target.value)}
                  placeholder="abc123...-us21"
                />
              </div>
              <div>
                <Label>Server Prefix</Label>
                <Input
                  value={serverPrefix}
                  onChange={(e) => setServerPrefix(e.target.value)}
                  placeholder="us21"
                />
              </div>
            </div>

            <div className="flex gap-2 flex-wrap">
              <Button variant="outline" onClick={handleTestAndLoad} disabled={loading || !apiKey || !serverPrefix}>
                {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
                Test & Load Audiences
              </Button>
              <Button variant="outline" onClick={() => setShowCreate(!showCreate)} disabled={!apiKey || !serverPrefix}>
                <Plus className="w-4 h-4 mr-2" /> Create New Audience
              </Button>
            </div>

            {showCreate && (
              <div className="p-4 border rounded-lg bg-muted/30 space-y-3">
                <Label>New audience name</Label>
                <Input
                  value={newAudienceName}
                  onChange={(e) => setNewAudienceName(e.target.value)}
                  placeholder={associations.find(a => a.id === selectedAssoc)?.name || "HOA Owners"}
                />
                <Button size="sm" onClick={handleCreateAudience} disabled={loading}>
                  {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
                  Create in Mailchimp
                </Button>
              </div>
            )}

            {audiences.length > 0 && (
              <div>
                <Label>Audience</Label>
                <Select value={selectedAudience} onValueChange={setSelectedAudience}>
                  <SelectTrigger><SelectValue placeholder="Pick an audience" /></SelectTrigger>
                  <SelectContent>
                    {audiences.map(a => (
                      <SelectItem key={a.id} value={a.id}>
                        {a.name} {a.stats?.member_count != null && `(${a.stats.member_count} members)`}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}

            {config?.audience_name && audiences.length === 0 && (
              <p className="text-sm text-muted-foreground">
                Currently linked: <span className="font-medium text-foreground">{config.audience_name}</span> — click "Test & Load" to change.
              </p>
            )}

            <div className="flex gap-2 pt-2">
              <Button onClick={handleSave} disabled={loading}>
                {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
                Save Configuration
              </Button>
              {config && (
                <Button variant="destructive" onClick={handleDisconnect} disabled={loading}>
                  Disconnect
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {config?.audience_id && (
        <Card>
          <CardHeader>
            <CardTitle>Sync Owners to Mailchimp</CardTitle>
            <CardDescription>
              Pushes all active owners with email to the linked audience. Existing members are updated; new members are added as subscribed.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm">
                  Audience: <span className="font-medium">{config.audience_name}</span>
                </p>
                <p className="text-sm text-muted-foreground">
                  {ownerCount} owner(s) will be synced.
                </p>
              </div>
              <Button onClick={handleSync} disabled={syncing}>
                {syncing ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
                Sync Now
              </Button>
            </div>

            {config.last_sync_at && (
              <>
                <Separator />
                <div className="space-y-1 text-sm">
                  <p className="text-muted-foreground">Last sync</p>
                  <p>{format(new Date(config.last_sync_at), "PPpp")}</p>
                  <div className="flex items-center gap-2 mt-2">
                    {config.last_sync_status === "success" && (
                      <Badge className="bg-green-500/15 text-green-700 border-green-500/30" variant="outline">
                        <CheckCircle2 className="w-3 h-3 mr-1" /> Success
                      </Badge>
                    )}
                    {config.last_sync_status === "partial" && (
                      <Badge className="bg-yellow-500/15 text-yellow-700 border-yellow-500/30" variant="outline">
                        <AlertCircle className="w-3 h-3 mr-1" /> Partial
                      </Badge>
                    )}
                    {config.last_sync_status === "failed" && (
                      <Badge variant="destructive">
                        <AlertCircle className="w-3 h-3 mr-1" /> Failed
                      </Badge>
                    )}
                    <span className="text-muted-foreground">{config.last_sync_count} synced</span>
                  </div>
                  {config.last_sync_error && (
                    <p className="text-xs text-destructive mt-2 break-all">{config.last_sync_error}</p>
                  )}
                </div>
              </>
            )}
          </CardContent>
        </Card>
      )}

      {selectedAssoc && !config?.audience_id && (
        <Card className="border-dashed">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-muted-foreground"><Send className="w-5 h-5" /> Send Campaign via Mailchimp</CardTitle>
            <CardDescription>
              Save your Mailchimp credentials and select an audience above to unlock the campaign sender.
            </CardDescription>
          </CardHeader>
        </Card>
      )}

      {config?.audience_id && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2"><Send className="w-5 h-5" /> Send Campaign via Mailchimp</CardTitle>
            <CardDescription>
              Compose and send an email campaign directly through Mailchimp to <span className="font-medium text-foreground">{config.audience_name}</span>. You can send immediately or save as a draft to review in Mailchimp.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid md:grid-cols-2 gap-4">
              <div>
                <Label>Subject Line</Label>
                <Input value={campaignSubject} onChange={(e) => setCampaignSubject(e.target.value)} placeholder="Important community update" />
              </div>
              <div>
                <Label>From Name</Label>
                <Input value={campaignFromName} onChange={(e) => setCampaignFromName(e.target.value)} placeholder={associations.find(a => a.id === selectedAssoc)?.name || "HOA Board"} />
              </div>
            </div>
            <div>
              <Label>Reply-To Email</Label>
              <Input type="email" value={campaignReplyTo} onChange={(e) => setCampaignReplyTo(e.target.value)} placeholder="board@yourhoa.com" />
            </div>
            <div>
              <Label>Email Content (HTML)</Label>
              <Textarea
                value={campaignHtml}
                onChange={(e) => setCampaignHtml(e.target.value)}
                placeholder="<h1>Hello owners</h1><p>Your message here...</p>"
                rows={10}
                className="font-mono text-xs"
              />
              <p className="text-xs text-muted-foreground mt-1">
                Plain HTML supported. Mailchimp automatically appends required unsubscribe footers.
              </p>
            </div>

            <div className="flex flex-wrap gap-2 pt-2">
              <Button onClick={() => handleSendCampaign(true)} disabled={sendingCampaign}>
                {sendingCampaign ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Send className="w-4 h-4 mr-2" />}
                Send Now to {ownerCount} Recipients
              </Button>
              <Button variant="outline" onClick={() => handleSendCampaign(false)} disabled={sendingCampaign}>
                Save as Draft in Mailchimp
              </Button>
            </div>

            {lastCampaign && (
              <div className="p-3 rounded-md bg-muted/40 border text-sm flex items-center justify-between gap-2">
                <span>
                  {lastCampaign.sent ? "✓ Campaign sent successfully" : "✓ Draft saved in Mailchimp"}
                </span>
                {lastCampaign.web_id && (
                  <a
                    href={`https://${config.server_prefix}.admin.mailchimp.com/campaigns/edit?id=${lastCampaign.web_id}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-primary hover:underline inline-flex items-center gap-1"
                  >
                    Open in Mailchimp <ExternalLink className="w-3 h-3" />
                  </a>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
