import { useT } from "@agent-native/core/client/i18n";
import {
  IconX,
  IconCheck,
  IconLoader2,
  IconDatabase,
  IconCloud,
  IconChevronRight,
} from "@tabler/icons-react";
import { useState, useRef, useCallback } from "react";

interface CloudUpgradeProps {
  title?: string;
  description?: string;
  onClose?: () => void;
}

interface Provider {
  id: string;
  name: string;
  descriptionKey: string;
  urlPrefix: string;
  needsAuthToken: boolean;
  stepKeys: string[];
}

const PROVIDERS: Provider[] = [
  {
    id: "turso",
    name: "Turso",
    descriptionKey: "cloudUpgrade.providers.turso.description",
    urlPrefix: "libsql://",
    needsAuthToken: true,
    stepKeys: ["step1", "step2", "step3", "step4", "step5"],
  },
  {
    id: "neon",
    name: "Neon",
    descriptionKey: "cloudUpgrade.providers.neon.description",
    urlPrefix: "postgres://",
    needsAuthToken: false,
    stepKeys: ["step1", "step2", "step3", "step4", "step5"],
  },
  {
    id: "supabase",
    name: "Supabase",
    descriptionKey: "cloudUpgrade.providers.supabase.description",
    urlPrefix: "postgres://",
    needsAuthToken: false,
    stepKeys: ["step1", "step2", "step3", "step4", "step5"],
  },
  {
    id: "d1",
    name: "Cloudflare D1", // i18n-ignore stable provider name
    descriptionKey: "cloudUpgrade.providers.d1.description",
    urlPrefix: "d1://",
    needsAuthToken: true,
    stepKeys: ["step1", "step2", "step3", "step4", "step5", "step6"],
  },
];

export function CloudUpgrade({
  title = "Share Publicly",
  description = "To share content publicly, connect a cloud database.",
  onClose,
}: CloudUpgradeProps) {
  const t = useT();
  const [selectedProvider, setSelectedProvider] = useState<string | null>(null);
  const [dbUrl, setDbUrl] = useState("");
  const [authToken, setAuthToken] = useState("");
  const [status, setStatus] = useState<
    "idle" | "saving" | "polling" | "success" | "error"
  >("idle");
  const [errorMsg, setErrorMsg] = useState("");
  const connectingRef = useRef(false);

  const provider = PROVIDERS.find((p) => p.id === selectedProvider);

  const handleConnect = useCallback(async () => {
    if (connectingRef.current) return;
    connectingRef.current = true;

    if (!dbUrl.trim()) {
      setErrorMsg(
        "Database settings are deployment-level. Configure DATABASE_URL with your host and redeploy the app.",
      );
      setStatus("error");
      connectingRef.current = false;
      return;
    }

    try {
      setStatus("error");
      setErrorMsg("");
      throw new Error(
        "Database settings are deployment-level. Configure DATABASE_URL and DATABASE_AUTH_TOKEN with your host, redeploy, then check sharing again.",
      );
    } catch (e) {
      setErrorMsg(
        e instanceof Error ? e.message : t("cloudUpgrade.connectionFailed"),
      );
      setStatus("error");
    } finally {
      connectingRef.current = false;
    }
  }, [dbUrl, authToken, t]);

  const isConnecting = status === "saving" || status === "polling";

  return (
    <div className="w-full max-w-lg rounded-xl border border-zinc-200 bg-white p-6 shadow-sm dark:border-zinc-800 dark:bg-zinc-950">
      {/* Header */}
      <div className="mb-4 flex items-start justify-between">
        <div className="flex items-center gap-2">
          <IconCloud className="h-5 w-5 text-blue-500" />
          <h3 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
            {title}
          </h3>
        </div>
        {onClose && (
          <button
            onClick={onClose}
            className="rounded-md p-1 text-zinc-400 hover:bg-zinc-100 hover:text-zinc-600 dark:hover:bg-zinc-800 dark:hover:text-zinc-300"
          >
            <IconX className="h-4 w-4" />
          </button>
        )}
      </div>

      <p className="mb-5 text-sm text-zinc-500 dark:text-zinc-400">
        {description}
      </p>

      {/* Provider selection */}
      <div className="mb-5 grid grid-cols-2 gap-2">
        {PROVIDERS.map((p) => (
          <button
            key={p.id}
            onClick={() => setSelectedProvider(p.id)}
            className={`flex flex-col items-start rounded-lg border px-3 py-2.5 text-left transition-colors ${
              selectedProvider === p.id
                ? "border-blue-500 bg-blue-50 dark:border-blue-400 dark:bg-blue-950/30"
                : "border-zinc-200 hover:border-zinc-300 dark:border-zinc-700 dark:hover:border-zinc-600"
            }`}
          >
            <span
              className={`text-sm font-medium ${
                selectedProvider === p.id
                  ? "text-blue-700 dark:text-blue-300"
                  : "text-zinc-900 dark:text-zinc-100"
              }`}
            >
              {p.name}
            </span>
            <span className="mt-0.5 text-xs text-zinc-500 dark:text-zinc-400">
              {t(p.descriptionKey)}
            </span>
          </button>
        ))}
      </div>

      {/* Provider setup steps */}
      {provider && (
        <div className="mb-5 rounded-lg border border-zinc-100 bg-zinc-50 p-3 dark:border-zinc-800 dark:bg-zinc-900">
          <p className="mb-2 text-xs font-medium uppercase tracking-wide text-zinc-500 dark:text-zinc-400">
            {t("cloudUpgrade.setupSteps")}
          </p>
          <ol className="space-y-1">
            {provider.stepKeys.map((stepKey, i) => (
              <li
                key={i}
                className="flex items-start gap-2 text-xs text-zinc-600 dark:text-zinc-300"
              >
                <IconChevronRight className="mt-0.5 h-3 w-3 shrink-0 text-zinc-400" />
                <span className="font-mono">
                  {t(`cloudUpgrade.providers.${provider.id}.steps.${stepKey}`)}
                </span>
              </li>
            ))}
          </ol>
        </div>
      )}

      {/* Credential inputs */}
      <div className="space-y-3">
        <div>
          <label className="mb-1 block text-xs font-medium text-zinc-700 dark:text-zinc-300">
            DATABASE_URL
          </label>
          <input
            type="text"
            placeholder={
              provider?.urlPrefix
                ? `${provider.urlPrefix}...`
                : "libsql://... or postgres://..."
            }
            value={dbUrl}
            onChange={(e) => setDbUrl(e.target.value)}
            disabled={isConnecting}
            className="w-full rounded-md border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-900 placeholder:text-zinc-400 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:placeholder:text-zinc-500"
          />
        </div>

        {(!provider || provider.needsAuthToken) && (
          <div>
            <label className="mb-1 block text-xs font-medium text-zinc-700 dark:text-zinc-300">
              DATABASE_AUTH_TOKEN
              {provider && !provider.needsAuthToken && (
                <span className="ml-1 text-zinc-400">
                  {t("bookingLinks.optional")}
                </span>
              )}
            </label>
            <input
              type="password"
              placeholder={t("cloudUpgrade.authToken")}
              value={authToken}
              onChange={(e) => setAuthToken(e.target.value)}
              disabled={isConnecting}
              className="w-full rounded-md border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-900 placeholder:text-zinc-400 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:placeholder:text-zinc-500"
            />
          </div>
        )}
      </div>

      {/* Error message */}
      {status === "error" && errorMsg && (
        <p className="mt-3 text-xs text-red-600 dark:text-red-400">
          {errorMsg}
        </p>
      )}

      {/* Success message */}
      {status === "success" && (
        <div className="mt-3 flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400">
          <IconCheck className="h-3.5 w-3.5" />
          <span>{t("cloudUpgrade.connectedReloading")}</span>
        </div>
      )}

      {/* Connect button */}
      <button
        onClick={handleConnect}
        disabled={isConnecting || !dbUrl.trim() || status === "success"}
        className="mt-4 flex w-full items-center justify-center gap-2 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {isConnecting ? (
          <>
            <IconLoader2 className="h-4 w-4 animate-spin" />
            <span>
              {status === "saving"
                ? t("cloudUpgrade.savingCredentials")
                : t("cloudUpgrade.testingConnection")}
            </span>
          </>
        ) : (
          <>
            <IconDatabase className="h-4 w-4" />
            <span>{t("cloudUpgrade.testAndConnect")}</span>
          </>
        )}
      </button>
    </div>
  );
}
