"use client";

import { useEffect, useState, useCallback } from "react";
import { useSearchParams } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useAlertConfirm } from "@/components/ui/alert-dialog";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";

interface MailAccount {
  id: string;
  email: string;
  name?: string;
  picture?: string;
  entitySlug?: string;
  label?: string;
  connectedAt: string;
}

export function MailAccounts() {
  const [accounts, setAccounts] = useState<MailAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>("");
  const params = useSearchParams();
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const justConnected = params.get("google_connected");
  const googleError = params.get("google_error");

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const resp = await fetch("/api/google/accounts");
      const data = await resp.json();
      if (!resp.ok) throw new Error(data.error || "Failed");
      setAccounts(data.accounts ?? []);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Unknown error");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    const t = setTimeout(() => void refresh(), 0);
    return () => clearTimeout(t);
  }, [refresh]);

  async function setEntity(id: string, entitySlug: string) {
    await fetch("/api/google/accounts", {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ id, entitySlug }),
    });
    setAccounts((prev) => prev.map((a) => (a.id === id ? { ...a, entitySlug } : a)));
  }

  async function setLabel(id: string, label: string) {
    await fetch("/api/google/accounts", {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ id, label }),
    });
    setAccounts((prev) => prev.map((a) => (a.id === id ? { ...a, label } : a)));
  }

  async function disconnect(id: string) {
    const ok = await confirmAlert({
      title: `Disconnect ${id}?`,
      description: "You'll need to re-authorize to reconnect.",
      actionLabel: "Disconnect",
      destructive: true,
    });
    if (!ok) return;
    await fetch(`/api/google/accounts?id=${encodeURIComponent(id)}`, { method: "DELETE" });
    setAccounts((prev) => prev.filter((a) => a.id !== id));
  }

  return (
    <>
    <div className="space-y-6 max-w-4xl">
      {(justConnected || googleError) && (
        <Card className={googleError ? "border-destructive/30 bg-destructive/5" : "border-green-500/30 bg-green-50/30 dark:bg-green-900/10"}>
          <CardContent className="p-4 text-sm">
            {googleError ? (
              <>
                <strong className="text-destructive">Google error:</strong> {googleError}
              </>
            ) : (
              <>
                <strong className="text-green-700 dark:text-green-400">Connected:</strong> {justConnected}
              </>
            )}
          </CardContent>
        </Card>
      )}

      <Card>
        <CardContent className="p-6 flex items-center justify-between flex-wrap gap-3">
          <div>
            <h2 className="text-base font-semibold">Connect a Gmail account</h2>
            <p className="mt-1 text-sm text-muted-foreground max-w-2xl">
              Each account you connect grants SAG Manager read + label access. Refresh tokens stay on the server in <code className="text-xs">.data/google-accounts.json</code> (mode 600, gitignored). Disconnect anytime.
            </p>
          </div>
          <Button asChild variant="brand">
            <a href="/api/google/auth?returnTo=%2Fapp%2Fmail%2Faccounts">+ Connect Gmail</a>
          </Button>
        </CardContent>
      </Card>

      {error && (
        <Card>
          <CardContent className="p-4 text-sm text-destructive">{error}</CardContent>
        </Card>
      )}

      {loading ? (
        <Card><CardContent className="p-6 text-sm text-muted-foreground">Loading...</CardContent></Card>
      ) : accounts.length === 0 ? (
        <Card>
          <CardContent className="p-12 text-center">
            <div className="text-5xl mb-3">📬</div>
            <p className="text-base font-medium">No accounts connected yet</p>
            <p className="mt-1 text-sm text-muted-foreground max-w-md mx-auto">
              Click <strong>Connect Gmail</strong> above. You can connect 8+ accounts and map each to a SAG entity. Setup details in <code className="text-xs">GMAIL_SETUP.md</code>.
            </p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-3">
          {accounts.map((a) => {
            const org = a.entitySlug ? ALL_ORGANIZATIONS.find((o) => o.slug === a.entitySlug) : undefined;
            return (
              <Card key={a.id}>
                <CardContent className="p-5">
                  <div className="flex items-start gap-4 flex-wrap">
                    {a.picture && (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={a.picture}
                        alt={a.email}
                        className="w-12 h-12 rounded-full shrink-0"
                        referrerPolicy="no-referrer"
                      />
                    )}
                    <div className="flex-1 min-w-0">
                      <div className="font-semibold">{a.name ?? a.email}</div>
                      <div className="text-xs text-muted-foreground font-mono">{a.email}</div>
                      <div className="mt-1 flex items-center gap-2 flex-wrap">
                        <Badge variant="success" className="text-[10px]">Connected</Badge>
                        <span className="text-[10px] text-muted-foreground">
                          Since {new Date(a.connectedAt).toLocaleDateString()}
                        </span>
                        {org && (
                          <Badge variant="info" className="text-[10px]">
                            {org.emoji} {org.name}
                          </Badge>
                        )}
                      </div>
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => disconnect(a.id)}>
                      Disconnect
                    </Button>
                  </div>

                  <div className="mt-4 grid gap-3 md:grid-cols-2">
                    <div>
                      <label className="text-xs text-muted-foreground">Assigned entity</label>
                      <select
                        value={a.entitySlug ?? ""}
                        onChange={(e) => setEntity(a.id, e.target.value)}
                        className="mt-1 w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
                      >
                        <option value="">— Unassigned —</option>
                        {ALL_ORGANIZATIONS.map((o) => (
                          <option key={o.slug} value={o.slug}>
                            {o.emoji} {o.name}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="text-xs text-muted-foreground">Display label (optional)</label>
                      <Input
                        defaultValue={a.label ?? ""}
                        onBlur={(e) => setLabel(a.id, e.target.value)}
                        placeholder="e.g. WCCG general inbox"
                        className="mt-1"
                      />
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
    <AlertConfirmPortal />
    </>
  );
}
