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, Plug, Send, ExternalLink, Users } from "lucide-react";
import { format } from "date-fns";

interface Association { id: string; name: string; }
interface SegmentRow {
  association_id: string;
  segment_uuid: string | null;
  segment_name: string | null;
  last_sync_at: string | null;
  last_sync_status: string | null;
  last_sync_count: number | null;
  last_sync_error: string | null;
}

const REACH_DASHBOARD_URL = "https://hpanel.hostinger.com/reach";

export default function HostingerReachPage() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState<Association[]>([]);
  const [selectedAssoc, setSelectedAssoc] = useState<string>("");

  // Global token config
  const [configId, setConfigId] = useState<string | null>(null);
  const [apiToken, setApiToken] = useState("");
  const [testing, setTesting] = useState(false);
  const [savingToken, setSavingToken] = useState(false);

  // Per-association sync state
  const [ownerCount, setOwnerCount] = useState<number>(0);
  const [segment, setSegment] = useState<SegmentRow | null>(null);
  const [syncing, setSyncing] = useState(false);

  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);
      const { data: cfg } = await supabase
        .from("hostinger_reach_config").select("id").order("updated_at", { ascending: false }).limit(1).maybeSingle();
      setConfigId(cfg?.id ?? null);
    })();
  }, []);

  useEffect(() => {
    if (!selectedAssoc) return;
    loadOwnerCount(selectedAssoc);
    loadSegment(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 loadSegment = async (id: string) => {
    const { data } = await supabase.from("hostinger_reach_segments").select("*").eq("association_id", id).maybeSingle();
    setSegment((data as SegmentRow) ?? null);
  };

  const handleTest = async () => {
    setTesting(true);
    try {
      const { data, error } = await supabase.functions.invoke("reach-connection", {
        body: apiToken.trim() ? { api_token: apiToken.trim() } : {},
      });
      if (error) throw error;
      if (!data.success) throw new Error(data.error || "Connection failed");
      toast({ title: "Connected", description: `Reach reachable — ${data.segment_count} segment(s).` });
    } catch (e: any) {
      toast({ variant: "destructive", title: "Connection failed", description: e.message });
    } finally {
      setTesting(false);
    }
  };

  const handleSaveToken = async () => {
    if (!apiToken.trim()) {
      toast({ variant: "destructive", title: "Missing token", description: "Paste your Hostinger Reach API token." });
      return;
    }
    setSavingToken(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      const payload = { api_token: apiToken.trim(), created_by: user?.id };
      const { error } = configId
        ? await supabase.from("hostinger_reach_config").update(payload).eq("id", configId)
        : await supabase.from("hostinger_reach_config").insert(payload);
      if (error) throw error;
      const { data: cfg } = await supabase
        .from("hostinger_reach_config").select("id").order("updated_at", { ascending: false }).limit(1).maybeSingle();
      setConfigId(cfg?.id ?? null);
      setApiToken("");
      toast({ title: "Saved", description: "Hostinger Reach API token stored." });
    } catch (e: any) {
      toast({ variant: "destructive", title: "Save failed", description: e.message });
    } finally {
      setSavingToken(false);
    }
  };

  const handleSync = async () => {
    if (!configId) {
      toast({ variant: "destructive", title: "Not connected", description: "Save your Reach API token first." });
      return;
    }
    setSyncing(true);
    try {
      const { data, error } = await supabase.functions.invoke("reach-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` : ""} → segment "${data.segment_name}".`,
      });
      loadSegment(selectedAssoc);
    } catch (e: any) {
      toast({ variant: "destructive", title: "Sync failed", description: e.message });
    } finally {
      setSyncing(false);
    }
  };

  const assocName = associations.find((a) => a.id === selectedAssoc)?.name;

  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">Hostinger Reach</h1>
          <p className="text-sm text-muted-foreground">
            Push each association's owners into Hostinger Reach as contacts, organized into a per-association segment. Compose and send campaigns from the Reach dashboard.
          </p>
        </div>
      </div>

      {/* Connection */}
      <Card>
        <CardHeader className="flex flex-row items-start justify-between">
          <div>
            <CardTitle className="flex items-center gap-2"><Plug className="w-5 h-5" /> API Connection</CardTitle>
            <CardDescription>
              One account-wide token. Create it in hPanel → Reach → API. It's stored securely and never shown again after saving.
            </CardDescription>
          </div>
          {configId && (
            <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>
            <Label>Hostinger Reach API Token</Label>
            <Input
              type="password"
              value={apiToken}
              onChange={(e) => setApiToken(e.target.value)}
              placeholder={configId ? "•••••••• (saved) — paste a new token to replace" : "Paste your API token"}
            />
          </div>
          <div className="flex gap-2 flex-wrap">
            <Button variant="outline" onClick={handleTest} disabled={testing}>
              {testing ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
              Test Connection
            </Button>
            <Button onClick={handleSaveToken} disabled={savingToken || !apiToken.trim()}>
              {savingToken ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
              {configId ? "Replace Token" : "Save Token"}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Sync */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><Users className="w-5 h-5" /> Sync Owners to Reach</CardTitle>
          <CardDescription>Each association's active owners (with email) are pushed as contacts and grouped into their own Reach segment.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label>Association</Label>
            <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>
          </div>

          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm">
                <span className="font-medium text-foreground">{ownerCount}</span> active owner(s) with email
                {segment?.segment_name && <> · segment: <span className="font-medium">{segment.segment_name}</span></>}
              </p>
              <p className="text-sm text-muted-foreground">Re-running is safe — existing contacts aren't duplicated.</p>
            </div>
            <Button onClick={handleSync} disabled={syncing || !configId}>
              {syncing ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
              Sync Now
            </Button>
          </div>

          {segment?.last_sync_at && (
            <>
              <Separator />
              <div className="space-y-1 text-sm">
                <p className="text-muted-foreground">Last sync</p>
                <p>{format(new Date(segment.last_sync_at), "PPpp")}</p>
                <div className="flex items-center gap-2 mt-2">
                  {segment.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>
                  )}
                  {segment.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>
                  )}
                  {segment.last_sync_status === "failed" && (
                    <Badge variant="destructive"><AlertCircle className="w-3 h-3 mr-1" /> Failed</Badge>
                  )}
                  <span className="text-muted-foreground">{segment.last_sync_count ?? 0} synced</span>
                </div>
                {segment.last_sync_error && (
                  <p className="text-xs text-destructive mt-2 break-all">{segment.last_sync_error}</p>
                )}
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* Campaigns live in Reach */}
      <Card className="border-dashed">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-muted-foreground"><Send className="w-5 h-5" /> Send Campaigns in Reach</CardTitle>
          <CardDescription>
            Hostinger Reach campaigns are composed and sent from the Reach dashboard. Sync owners here, then target the
            {assocName ? <> <span className="font-medium text-foreground">{assocName}</span></> : " association"} segment in Reach.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <a href={REACH_DASHBOARD_URL} target="_blank" rel="noopener noreferrer"
             className="text-primary hover:underline inline-flex items-center gap-1 text-sm">
            Open Hostinger Reach <ExternalLink className="w-3 h-3" />
          </a>
        </CardContent>
      </Card>
    </div>
  );
}
