"use client";

import { useEffect, useState } from "react";
import type { ChangeEvent } from "react";
import type { FormEvent } from "react";
import { formatDateTime } from "@/lib/dates";

type Instance = {
  id: string;
  name: string;
  base_url: string;
  auth_type: "api_key" | "basic";
  status: string;
  error_message: string | null;
  last_connected_at: string | null;
  last_sync_at: string | null;
  last_sync_status: string | null;
  last_sync_error: string | null;
  last_sync_subscriptions: number;
  last_sync_domains: number;
  auto_sync_enabled: boolean;
  auto_sync_frequency_minutes: number;
  last_auto_sync_at: string | null;
  next_auto_sync_at: string | null;
  auto_sync_lock_until: string | null;
  health_enabled: boolean;
  health_status: "ok" | "degraded" | "down" | "unknown";
  health_last_checked_at: string | null;
  health_last_ok_at: string | null;
  health_last_error: string | null;
  health_last_latency_ms: number | null;
  health_check_frequency_minutes: number;
  health_next_check_at: string | null;
  health_lock_until: string | null;
};

type Subscription = {
  id: string;
  name: string | null;
  status: string | null;
  plesk_subscription_id: string;
  plesk_instance_id: string;
};

type Domain = {
  id: string;
  plesk_instance_id: string;
  subscription_id: string | null;
  subscription_name?: string | null;
  domain_name: string;
  status: string | null;
  hosting_type: string | null;
  source_created_at: string | null;
  aliases_count: number | null;
  updated_at: string;
};

type DomainSortKey =
  | "domain"
  | "status"
  | "hosting"
  | "created"
  | "aliases"
  | "last_seen"
  | "actions";

type Props = {
  instances: Instance[];
  subscriptions: Subscription[];
  domains: Domain[];
  autoSyncByInstance: Record<
    string,
    { status: string; created_at: string; error_message: string | null }
  >;
  healthEventsByInstance: Record<
    string,
    Array<{
      id: string;
      action: string;
      status: string;
      created_at: string;
      error_message: string | null;
      metadata: unknown;
    }>
  >;
};

function getHealthBadge(status: string | null) {
  const normalized = (status ?? "unknown").toLowerCase();

  if (normalized === "ok") {
    return { label: "OK", className: "bg-emerald-100 text-emerald-700" };
  }

  if (normalized === "degraded") {
    return { label: "Degraded", className: "bg-amber-100 text-amber-700" };
  }

  if (normalized === "down") {
    return { label: "Down", className: "bg-rose-100 text-rose-700" };
  }

  return { label: "Unknown", className: "bg-slate-100 text-slate-600" };
}

function mapHealthResult(action: string) {
  if (action === "health_check_ok") return "ok";
  if (action === "health_check_degraded") return "degraded";
  if (action === "health_check_failed") return "failed";
  return "started";
}

function getDomainStatusBadge(status: string | null) {
  const normalized = (status ?? "unknown").toLowerCase();

  if (normalized.includes("suspend") || normalized.includes("disabled")) {
    return "bg-rose-100 text-rose-700";
  }

  if (normalized.includes("expired")) {
    return "bg-amber-100 text-amber-700";
  }

  if (normalized.includes("active") || normalized.includes("enabled")) {
    return "bg-emerald-100 text-emerald-700";
  }

  if (normalized.includes("ok")) {
    return "bg-emerald-100 text-emerald-700";
  }

  return "bg-slate-100 text-slate-600";
}

function formatDomainStatusLabel(status: string | null) {
  const normalized = (status ?? "unknown").toLowerCase();

  if (normalized.includes("suspend")) return "Suspended";
  if (normalized.includes("disabled")) return "Disabled";
  if (normalized.includes("expired")) return "Expired";
  if (
    normalized.includes("active") ||
    normalized.includes("ok") ||
    normalized.includes("enabled")
  ) {
    return "Active";
  }

  return "Unknown";
}

function isDomainSuspended(status: string | null) {
  const normalized = (status ?? "unknown").toLowerCase();
  return normalized.includes("suspend") || normalized.includes("disabled");
}

function isDomainActive(status: string | null) {
  const normalized = (status ?? "unknown").toLowerCase();
  return (
    normalized.includes("active") ||
    normalized.includes("ok") ||
    normalized.includes("enabled")
  );
}

function getDomainHref(domainName: string) {
  const normalized = domainName.trim();
  if (/^https?:\/\//i.test(normalized)) return normalized;
  return `https://${normalized}`;
}

function getLatestTimestamp(values: Array<string | null | undefined>) {
  let latest: string | null = null;
  let latestMs = Number.NEGATIVE_INFINITY;

  for (const value of values) {
    if (!value) continue;
    const ms = new Date(value).getTime();
    if (Number.isNaN(ms)) continue;
    if (ms > latestMs) {
      latestMs = ms;
      latest = value;
    }
  }

  return latest;
}

export function DashboardControls({
  instances,
  subscriptions,
  domains,
  autoSyncByInstance,
  healthEventsByInstance,
}: Props) {
  const hasInstances = instances.length > 0;
  const autoSyncFrequencyOptions = [15, 30, 60, 180, 360, 1440];
  const [instanceName, setInstanceName] = useState("");
  const [baseUrl, setBaseUrl] = useState("");
  const [authType, setAuthType] = useState<"api_key" | "basic">("api_key");
  const [apiKey, setApiKey] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [actionSubId, setActionSubId] = useState(subscriptions[0]?.id ?? "");
  const [actionType, setActionType] = useState<"suspend" | "unsuspend">(
    "suspend",
  );
  const [domainSearch, setDomainSearch] = useState("");
  const [domainStatus, setDomainStatus] = useState("all");
  const [domainSort, setDomainSort] = useState<{
    key: DomainSortKey;
    direction: "asc" | "desc";
  }>({ key: "domain", direction: "asc" });
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [isConnectPanelOpen, setIsConnectPanelOpen] = useState(!hasInstances);
  const [isInstancesPanelOpen, setIsInstancesPanelOpen] = useState(true);

  useEffect(() => {
    if (!hasInstances) {
      setIsConnectPanelOpen(true);
      return;
    }

    const savedState = window.localStorage.getItem(
      "dashboard_connect_panel_open",
    );

    if (savedState === "true") {
      setIsConnectPanelOpen(true);
      return;
    }

    if (savedState === "false") {
      setIsConnectPanelOpen(false);
      return;
    }

    setIsConnectPanelOpen(false);
  }, [hasInstances]);

  useEffect(() => {
    if (!hasInstances) return;

    window.localStorage.setItem(
      "dashboard_connect_panel_open",
      isConnectPanelOpen ? "true" : "false",
    );
  }, [hasInstances, isConnectPanelOpen]);

  useEffect(() => {
    if (!hasInstances) {
      setIsInstancesPanelOpen(true);
      return;
    }

    const savedState = window.localStorage.getItem(
      "dashboard_instances_panel_open",
    );

    if (savedState === "true") {
      setIsInstancesPanelOpen(true);
      return;
    }

    if (savedState === "false") {
      setIsInstancesPanelOpen(false);
      return;
    }

    setIsInstancesPanelOpen(true);
  }, [hasInstances]);

  useEffect(() => {
    if (!hasInstances) return;

    window.localStorage.setItem(
      "dashboard_instances_panel_open",
      isInstancesPanelOpen ? "true" : "false",
    );
  }, [hasInstances, isInstancesPanelOpen]);

  const healthCounts = instances.reduce(
    (acc, instance) => {
      if (instance.status === "connected") acc.connected += 1;
      else if (instance.status === "syncing") acc.syncing += 1;
      else acc.error += 1;
      return acc;
    },
    { connected: 0, syncing: 0, error: 0 },
  );

  const domainStatusOptions = Array.from(
    new Set(
      domains.map((domain) => (domain.status ?? "unknown").toLowerCase()),
    ),
  ).sort();

  const filteredDomains = domains.filter((domain) => {
    const normalizedStatus = (domain.status ?? "unknown").toLowerCase();
    const statusMatches =
      domainStatus === "all" || normalizedStatus === domainStatus;
    const term = domainSearch.trim().toLowerCase();
    const searchMatches =
      !term ||
      domain.domain_name.toLowerCase().includes(term) ||
      (domain.hosting_type ?? "").toLowerCase().includes(term);
    return statusMatches && searchMatches;
  });

  const sortedDomains = filteredDomains
    .map((domain, index) => ({ domain, index }))
    .sort((a, b) => {
      function compareNullable<T>(
        left: T | null | undefined,
        right: T | null | undefined,
        compare: (leftValue: T, rightValue: T) => number,
      ) {
        const leftMissing = left == null;
        const rightMissing = right == null;
        if (leftMissing && rightMissing) return 0;
        if (leftMissing) return 1;
        if (rightMissing) return -1;
        return compare(left, right);
      }

      function compareStrings(
        left: string | null | undefined,
        right: string | null | undefined,
      ) {
        return compareNullable(left, right, (l, r) =>
          l.localeCompare(r, undefined, { sensitivity: "base" }),
        );
      }

      function compareNumbers(
        left: number | null | undefined,
        right: number | null | undefined,
      ) {
        return compareNullable(left, right, (l, r) => l - r);
      }

      function toTime(value: string | null | undefined) {
        if (!value) return null;
        const time = new Date(value).getTime();
        return Number.isNaN(time) ? null : time;
      }

      const leftDomain = a.domain;
      const rightDomain = b.domain;

      let comparison = 0;

      if (domainSort.key === "domain") {
        comparison = compareStrings(
          leftDomain.domain_name,
          rightDomain.domain_name,
        );
      } else if (domainSort.key === "status") {
        comparison = compareStrings(
          formatDomainStatusLabel(leftDomain.status),
          formatDomainStatusLabel(rightDomain.status),
        );
      } else if (domainSort.key === "hosting") {
        comparison = compareStrings(
          leftDomain.hosting_type,
          rightDomain.hosting_type,
        );
      } else if (domainSort.key === "created") {
        comparison = compareNumbers(
          toTime(leftDomain.source_created_at),
          toTime(rightDomain.source_created_at),
        );
      } else if (domainSort.key === "aliases") {
        comparison = compareNumbers(
          leftDomain.aliases_count,
          rightDomain.aliases_count,
        );
      } else if (domainSort.key === "last_seen") {
        comparison = compareNumbers(
          toTime(leftDomain.updated_at),
          toTime(rightDomain.updated_at),
        );
      } else if (domainSort.key === "actions") {
        comparison = compareNumbers(
          leftDomain.subscription_id ? 1 : 0,
          rightDomain.subscription_id ? 1 : 0,
        );
      }

      if (comparison === 0) {
        comparison = a.index - b.index;
      }

      return domainSort.direction === "asc" ? comparison : comparison * -1;
    })
    .map((entry) => entry.domain);

  function toggleDomainSort(key: DomainSortKey) {
    setDomainSort((current) => {
      if (current.key === key) {
        return {
          key,
          direction: current.direction === "asc" ? "desc" : "asc",
        };
      }

      return { key, direction: "asc" };
    });
  }

  function getSortIndicator(key: DomainSortKey) {
    if (domainSort.key !== key) return "↕";
    return domainSort.direction === "asc" ? "↑" : "↓";
  }

  const instanceHealthSummary = instances.reduce(
    (acc, instance) => {
      const status = (instance.health_status ?? "unknown").toLowerCase();
      if (status === "ok") acc.ok += 1;
      else if (status === "degraded") acc.degraded += 1;
      else if (status === "down") acc.down += 1;
      else acc.unknown += 1;
      return acc;
    },
    { ok: 0, degraded: 0, down: 0, unknown: 0 },
  );

  const autoSyncEnabledCount = instances.filter(
    (instance) => instance.auto_sync_enabled,
  ).length;

  const latestInstanceSyncAt = getLatestTimestamp(
    instances.map((instance) => instance.last_sync_at),
  );

  const latestInstanceHealthCheckAt = getLatestTimestamp(
    instances.map((instance) => instance.health_last_checked_at),
  );

  async function runRequest(url: string, body?: unknown) {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: body ? JSON.stringify(body) : undefined,
    });

    const payload = await response.json().catch(() => ({}));
    if (!response.ok) {
      throw new Error(payload.error ?? "Request failed");
    }
    return payload;
  }

  async function onCreateInstance(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setLoading(true);
    setMessage(null);
    try {
      await runRequest("/api/plesk/instances", {
        name: instanceName,
        base_url: baseUrl,
        auth_type: authType,
        api_key: authType === "api_key" ? apiKey : undefined,
        username: authType === "basic" ? username : undefined,
        password: authType === "basic" ? password : undefined,
      });
      setMessage("Plesk instance connected.");
      window.location.reload();
    } catch (error) {
      setMessage(
        error instanceof Error ? error.message : "Could not connect instance",
      );
    } finally {
      setLoading(false);
    }
  }

  async function onSync(instanceId: string) {
    setLoading(true);
    setMessage(null);
    try {
      const payload = await runRequest(
        `/api/plesk/instances/${instanceId}/sync`,
      );
      setMessage("Plesk sync completed.");
      if (payload?.skipped) {
        setMessage(`Sync skipped (${payload.reason ?? "no reason"}).`);
      } else if (
        payload?.domainsUpserted != null ||
        payload?.subscriptionsUpserted != null
      ) {
        setMessage(
          `Plesk sync completed. Subscriptions: ${payload.subscriptionsUpserted ?? 0}, Domains: ${payload.domainsUpserted ?? 0}`,
        );
      }
      window.location.reload();
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "Sync failed");
    } finally {
      setLoading(false);
    }
  }

  async function onTestConnection(instanceId: string) {
    setLoading(true);
    setMessage(null);
    try {
      await runRequest(`/api/plesk/instances/${instanceId}/test`);
      setMessage("Connection test completed.");
      window.location.reload();
    } catch (error) {
      setMessage(
        error instanceof Error ? error.message : "Connection test failed",
      );
    } finally {
      setLoading(false);
    }
  }

  async function onRunHealthCheck(instanceId: string) {
    setLoading(true);
    setMessage(null);
    try {
      await runRequest(`/api/plesk/instances/${instanceId}/health`);
      setMessage("Health check completed.");
      window.location.reload();
    } catch (error) {
      setMessage(
        error instanceof Error ? error.message : "Health check failed",
      );
    } finally {
      setLoading(false);
    }
  }

  async function onUpdateAutoSync(
    instanceId: string,
    input: { auto_sync_enabled: boolean; auto_sync_frequency_minutes: number },
  ) {
    setLoading(true);
    setMessage(null);
    try {
      await runRequest(`/api/plesk/instances/${instanceId}/autosync`, input);
      setMessage("Auto-sync settings updated.");
      window.location.reload();
    } catch (error) {
      setMessage(
        error instanceof Error ? error.message : "Auto-sync update failed",
      );
    } finally {
      setLoading(false);
    }
  }

  async function onSubscriptionAction() {
    if (!actionSubId) return;
    setLoading(true);
    setMessage(null);
    try {
      await runRequest(`/api/plesk/subscriptions/${actionSubId}/action`, {
        action: actionType,
      });
      setMessage(`Subscription ${actionType} completed.`);
      window.location.reload();
    } catch (error) {
      setMessage(error instanceof Error ? error.message : "Action failed");
    } finally {
      setLoading(false);
    }
  }

  async function onDomainAction(
    domain: Domain,
    action: "suspend" | "unsuspend",
  ) {
    if (!domain.subscription_id) {
      setMessage(
        "Domain is not linked to a subscription yet. Run Sync Now (or backfill links) and try again.",
      );
      return;
    }

    setLoading(true);
    setMessage(null);
    try {
      await runRequest(`/api/plesk/domains/${domain.id}/action`, {
        action,
        subscription_id: domain.subscription_id,
      });
      setMessage("Domain action completed.");
      window.location.reload();
    } catch (error) {
      setMessage(
        error instanceof Error ? error.message : "Domain action failed",
      );
    } finally {
      setLoading(false);
    }
  }

  async function onCheckout() {
    setLoading(true);
    try {
      const payload = await runRequest("/api/stripe/checkout");
      if (payload.url) window.location.href = payload.url;
    } finally {
      setLoading(false);
    }
  }

  async function onPortal() {
    setLoading(true);
    try {
      const payload = await runRequest("/api/stripe/portal");
      if (payload.url) window.location.href = payload.url;
    } finally {
      setLoading(false);
    }
  }

  return (
    <section className="grid gap-4">
      <div className="grid gap-4 md:grid-cols-3">
        <div className="rounded-xl border border-emerald-200 bg-emerald-50 p-4">
          <p className="text-sm text-emerald-700">Connected</p>
          <p className="text-2xl font-semibold text-emerald-900">
            {healthCounts.connected}
          </p>
        </div>
        <div className="rounded-xl border border-amber-200 bg-amber-50 p-4">
          <p className="text-sm text-amber-700">Syncing</p>
          <p className="text-2xl font-semibold text-amber-900">
            {healthCounts.syncing}
          </p>
        </div>
        <div className="rounded-xl border border-rose-200 bg-rose-50 p-4">
          <p className="text-sm text-rose-700">Error/Other</p>
          <p className="text-2xl font-semibold text-rose-900">
            {healthCounts.error}
          </p>
        </div>
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <div className="rounded-xl border border-slate-200 bg-white p-4">
          <div className="flex items-center justify-between gap-3">
            <h2 className="text-lg font-semibold">
              {hasInstances
                ? "Connect another Plesk instance"
                : "Connect Plesk Instance"}
            </h2>
            {hasInstances ? (
              <button
                type="button"
                onClick={() => setIsConnectPanelOpen((open) => !open)}
                className="rounded border border-slate-300 px-3 py-1.5 text-xs font-medium text-slate-700"
              >
                {isConnectPanelOpen ? "Hide" : "Add instance"}
              </button>
            ) : null}
          </div>

          {!isConnectPanelOpen && hasInstances ? (
            <p className="mt-2 text-sm text-slate-500">
              Add another server when needed.
            </p>
          ) : null}

          {isConnectPanelOpen ? (
            <form onSubmit={onCreateInstance} className="mt-3 space-y-3">
              <input
                required
                value={instanceName}
                onChange={(e: ChangeEvent<HTMLInputElement>) =>
                  setInstanceName(e.target.value)
                }
                className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
                placeholder="Instance name"
              />
              <input
                required
                value={baseUrl}
                onChange={(e: ChangeEvent<HTMLInputElement>) =>
                  setBaseUrl(e.target.value)
                }
                className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
                placeholder="https://plesk.example.com"
              />
              <select
                value={authType}
                onChange={(e: ChangeEvent<HTMLSelectElement>) =>
                  setAuthType(e.target.value as "api_key" | "basic")
                }
                className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
              >
                <option value="api_key">API Key</option>
                <option value="basic">Basic</option>
              </select>
              {authType === "api_key" ? (
                <input
                  required
                  value={apiKey}
                  onChange={(e: ChangeEvent<HTMLInputElement>) =>
                    setApiKey(e.target.value)
                  }
                  className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
                  placeholder="Plesk API key"
                />
              ) : (
                <div className="grid gap-2 sm:grid-cols-2">
                  <input
                    required
                    value={username}
                    onChange={(e: ChangeEvent<HTMLInputElement>) =>
                      setUsername(e.target.value)
                    }
                    className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
                    placeholder="Plesk username"
                  />
                  <input
                    required
                    type="password"
                    value={password}
                    onChange={(e: ChangeEvent<HTMLInputElement>) =>
                      setPassword(e.target.value)
                    }
                    className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
                    placeholder="Plesk password"
                  />
                </div>
              )}
              <button
                disabled={loading}
                className="rounded bg-brand-600 px-3 py-2 text-sm text-white"
              >
                Save & Validate
              </button>
            </form>
          ) : null}
        </div>

        <div className="space-y-3 rounded-xl border border-slate-200 bg-white p-4">
          <div className="flex items-center justify-between gap-3">
            <h2 className="text-lg font-semibold">Plesk Instances</h2>
            {hasInstances ? (
              <button
                type="button"
                onClick={() => setIsInstancesPanelOpen((open) => !open)}
                className="rounded border border-slate-300 px-3 py-1.5 text-xs font-medium text-slate-700"
              >
                {isInstancesPanelOpen ? "Hide" : "Show"}
              </button>
            ) : null}
          </div>

          {!isInstancesPanelOpen && hasInstances ? (
            <div className="rounded border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-700">
              <p className="font-medium text-slate-900">
                {instances.length} instance{instances.length === 1 ? "" : "s"}
              </p>
              <p className="mt-1">
                Health — OK: {instanceHealthSummary.ok}, Degraded:{" "}
                {instanceHealthSummary.degraded}, Down:{" "}
                {instanceHealthSummary.down}, Unknown:{" "}
                {instanceHealthSummary.unknown}
              </p>
              <p className="mt-1">
                Auto-sync enabled on {autoSyncEnabledCount} instance
                {autoSyncEnabledCount === 1 ? "" : "s"}
              </p>
              <p className="mt-1">
                Last sync: {formatDateTime(latestInstanceSyncAt)}
              </p>
              <p className="mt-1">
                Last health check: {formatDateTime(latestInstanceHealthCheckAt)}
              </p>
            </div>
          ) : null}

          {isInstancesPanelOpen ? (
            <>
              <div className="space-y-2">
                {instances.length === 0 ? (
                  <p className="text-sm text-slate-500">
                    No Plesk instances connected yet.
                  </p>
                ) : (
                  instances.map((instance) => (
                    <div
                      key={instance.id}
                      className="rounded border border-slate-200 p-3"
                    >
                      {(() => {
                        const health = getHealthBadge(instance.health_status);

                        return (
                          <div className="flex items-start justify-between gap-2">
                            <div>
                              {autoSyncByInstance[instance.id] ? (
                                <span
                                  className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${
                                    autoSyncByInstance[instance.id].status ===
                                    "success"
                                      ? "bg-emerald-100 text-emerald-700"
                                      : "bg-rose-100 text-rose-700"
                                  }`}
                                >
                                  Auto-sync{" "}
                                  {autoSyncByInstance[instance.id].status}
                                </span>
                              ) : null}
                              <p className="text-sm font-semibold text-slate-900">
                                {instance.name}
                              </p>
                              <p className="text-xs text-slate-500">
                                {instance.base_url}
                              </p>
                              <p className="mt-1 text-xs text-slate-600">
                                Status:{" "}
                                <span className="font-medium">
                                  {instance.status}
                                </span>
                              </p>
                              <p className="text-xs text-slate-500">
                                Health:{" "}
                                <span
                                  title={
                                    instance.health_last_error ?? undefined
                                  }
                                  className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${health.className}`}
                                >
                                  {health.label}
                                </span>
                              </p>
                              <p className="text-xs text-slate-500">
                                Health last checked:{" "}
                                {formatDateTime(
                                  instance.health_last_checked_at,
                                )}
                              </p>
                              <p className="text-xs text-slate-500">
                                Health latency:{" "}
                                {instance.health_last_latency_ms != null
                                  ? `${instance.health_last_latency_ms} ms`
                                  : "—"}
                              </p>
                              <p className="text-xs text-slate-500">
                                Subscriptions:{" "}
                                {instance.last_sync_subscriptions ?? 0}
                              </p>
                              <p className="text-xs text-slate-500">
                                Domains: {instance.last_sync_domains ?? 0}
                              </p>
                              <p className="text-xs text-slate-500">
                                Last sync status:{" "}
                                <span
                                  className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${
                                    instance.last_sync_status === "success"
                                      ? "bg-emerald-100 text-emerald-700"
                                      : instance.last_sync_status ===
                                            "failed" ||
                                          instance.last_sync_status === "error"
                                        ? "bg-rose-100 text-rose-700"
                                        : "bg-slate-100 text-slate-600"
                                  }`}
                                >
                                  {instance.last_sync_status ?? "unknown"}
                                </span>
                              </p>
                              <p className="text-xs text-slate-500">
                                Last sync time:{" "}
                                {formatDateTime(instance.last_sync_at)}
                              </p>
                              <p className="text-xs text-slate-500">
                                Last connected:{" "}
                                {instance.last_connected_at
                                  ? formatDateTime(instance.last_connected_at)
                                  : "never"}
                              </p>
                              <p className="text-xs text-slate-500">
                                Auto-sync:{" "}
                                {instance.auto_sync_enabled
                                  ? "Enabled"
                                  : "Disabled"}
                              </p>
                              <p className="text-xs text-slate-500">
                                Auto-sync frequency:{" "}
                                {instance.auto_sync_frequency_minutes ?? 60} min
                              </p>
                              <p className="text-xs text-slate-500">
                                Last auto-sync:{" "}
                                {formatDateTime(instance.last_auto_sync_at)}
                              </p>
                              <p className="text-xs text-slate-500">
                                Next auto-sync:{" "}
                                {formatDateTime(instance.next_auto_sync_at)}
                              </p>
                              <p className="text-xs text-slate-500">
                                Lock status:{" "}
                                {instance.auto_sync_lock_until &&
                                new Date(
                                  instance.auto_sync_lock_until,
                                ).getTime() > Date.now()
                                  ? "Sync in progress"
                                  : "Idle"}
                              </p>
                              {autoSyncByInstance[instance.id] ? (
                                <p className="text-xs text-slate-500">
                                  Last auto-sync:{" "}
                                  {formatDateTime(
                                    autoSyncByInstance[instance.id].created_at,
                                  )}
                                </p>
                              ) : null}
                              {instance.error_message ? (
                                <p className="mt-1 text-xs text-rose-600">
                                  {instance.error_message}
                                </p>
                              ) : null}
                              {instance.last_sync_error ? (
                                <p className="mt-1 text-xs text-rose-600">
                                  Last sync error: {instance.last_sync_error}
                                </p>
                              ) : null}
                              {autoSyncByInstance[instance.id]
                                ?.error_message ? (
                                <p className="mt-1 text-xs text-rose-600">
                                  Auto-sync error:{" "}
                                  {
                                    autoSyncByInstance[instance.id]
                                      .error_message
                                  }
                                </p>
                              ) : null}
                              {instance.health_last_error ? (
                                <p
                                  className="mt-1 text-xs text-rose-600"
                                  title={instance.health_last_error}
                                >
                                  Health error: {instance.health_last_error}
                                </p>
                              ) : null}
                            </div>
                            <div className="flex flex-col gap-2">
                              <div className="flex items-center gap-2">
                                <label className="text-xs text-slate-600">
                                  Auto-sync
                                </label>
                                <input
                                  type="checkbox"
                                  checked={instance.auto_sync_enabled}
                                  onChange={(
                                    e: ChangeEvent<HTMLInputElement>,
                                  ) =>
                                    onUpdateAutoSync(instance.id, {
                                      auto_sync_enabled: e.target.checked,
                                      auto_sync_frequency_minutes:
                                        instance.auto_sync_frequency_minutes ??
                                        60,
                                    })
                                  }
                                  disabled={loading}
                                />
                              </div>
                              <select
                                value={String(
                                  instance.auto_sync_frequency_minutes ?? 60,
                                )}
                                onChange={(e: ChangeEvent<HTMLSelectElement>) =>
                                  onUpdateAutoSync(instance.id, {
                                    auto_sync_enabled:
                                      instance.auto_sync_enabled,
                                    auto_sync_frequency_minutes: Number(
                                      e.target.value,
                                    ),
                                  })
                                }
                                disabled={loading}
                                className="rounded border px-2 py-1 text-xs"
                              >
                                {autoSyncFrequencyOptions.map((minutes) => (
                                  <option key={minutes} value={minutes}>
                                    Every {minutes} min
                                  </option>
                                ))}
                              </select>
                              <button
                                onClick={() => onTestConnection(instance.id)}
                                disabled={loading}
                                className="rounded border px-3 py-1.5 text-xs"
                              >
                                Test Connection
                              </button>
                              <button
                                onClick={() => onRunHealthCheck(instance.id)}
                                disabled={loading}
                                className="rounded border px-3 py-1.5 text-xs"
                              >
                                Run Health Check
                              </button>
                              <button
                                onClick={() => onSync(instance.id)}
                                disabled={loading}
                                className="rounded border px-3 py-1.5 text-xs"
                              >
                                Sync Now
                              </button>
                            </div>
                          </div>
                        );
                      })()}

                      <div className="mt-3 rounded border border-slate-100 bg-slate-50 p-3">
                        <p className="text-xs font-semibold uppercase tracking-wide text-slate-600">
                          Health Panel
                        </p>
                        <div className="mt-2 grid gap-1 text-xs text-slate-600 sm:grid-cols-2">
                          <p>
                            Current Status:{" "}
                            <span className="font-medium">
                              {getHealthBadge(instance.health_status).label}
                            </span>
                          </p>
                          <p>
                            Last Checked:{" "}
                            <span className="font-medium">
                              {formatDateTime(instance.health_last_checked_at)}
                            </span>
                          </p>
                          <p>
                            Last Successful Check:{" "}
                            <span className="font-medium">
                              {formatDateTime(instance.health_last_ok_at)}
                            </span>
                          </p>
                          <p>
                            Latency:{" "}
                            <span className="font-medium">
                              {instance.health_last_latency_ms != null
                                ? `${instance.health_last_latency_ms} ms`
                                : "—"}
                            </span>
                          </p>
                          <p className="sm:col-span-2">
                            Last Error:{" "}
                            <span className="font-medium">
                              {instance.health_last_error ?? "—"}
                            </span>
                          </p>
                        </div>

                        <div className="mt-3 overflow-x-auto">
                          <table className="min-w-full text-left text-xs">
                            <thead>
                              <tr className="border-b border-slate-200 text-slate-500">
                                <th className="px-2 py-1">Time</th>
                                <th className="px-2 py-1">Event</th>
                                <th className="px-2 py-1">Result</th>
                                <th className="px-2 py-1">Message</th>
                              </tr>
                            </thead>
                            <tbody>
                              {(healthEventsByInstance[instance.id] ?? [])
                                .length === 0 ? (
                                <tr>
                                  <td
                                    className="px-2 py-2 text-slate-500"
                                    colSpan={4}
                                  >
                                    No health events yet.
                                  </td>
                                </tr>
                              ) : (
                                (healthEventsByInstance[instance.id] ?? []).map(
                                  (event) => (
                                    <tr
                                      key={event.id}
                                      className="border-b border-slate-100 align-top"
                                    >
                                      <td className="px-2 py-1">
                                        {formatDateTime(event.created_at)}
                                      </td>
                                      <td className="px-2 py-1">
                                        {event.action}
                                      </td>
                                      <td className="px-2 py-1">
                                        {mapHealthResult(event.action)}
                                      </td>
                                      <td className="px-2 py-1">
                                        {event.error_message ?? "—"}
                                        {event.metadata ? (
                                          <details>
                                            <summary className="cursor-pointer text-[11px] text-brand-700">
                                              metadata
                                            </summary>
                                            <pre className="mt-1 max-w-[440px] overflow-auto rounded bg-white p-2 text-[10px] text-slate-700">
                                              {JSON.stringify(
                                                event.metadata,
                                                null,
                                                2,
                                              )}
                                            </pre>
                                          </details>
                                        ) : null}
                                      </td>
                                    </tr>
                                  ),
                                )
                              )}
                            </tbody>
                          </table>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium">
                  Subscription Action
                </label>
                <select
                  value={actionSubId}
                  onChange={(e: ChangeEvent<HTMLSelectElement>) =>
                    setActionSubId(e.target.value)
                  }
                  className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
                >
                  {subscriptions.map((subscription) => (
                    <option key={subscription.id} value={subscription.id}>
                      {subscription.name ?? subscription.plesk_subscription_id}
                    </option>
                  ))}
                </select>
                <select
                  value={actionType}
                  onChange={(e: ChangeEvent<HTMLSelectElement>) =>
                    setActionType(e.target.value as "suspend" | "unsuspend")
                  }
                  className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
                >
                  <option value="suspend">Suspend</option>
                  <option value="unsuspend">Unsuspend</option>
                </select>
                <button
                  onClick={onSubscriptionAction}
                  disabled={loading || !actionSubId}
                  className="rounded border px-3 py-2 text-sm"
                >
                  Execute Action
                </button>
              </div>

              <div className="flex gap-2 pt-2">
                <button
                  onClick={onCheckout}
                  disabled={loading}
                  className="rounded bg-brand-600 px-3 py-2 text-sm text-white"
                >
                  Start Checkout
                </button>
                <button
                  onClick={onPortal}
                  disabled={loading}
                  className="rounded border px-3 py-2 text-sm"
                >
                  Billing Portal
                </button>
              </div>

              {message ? (
                <p className="text-sm text-slate-600">{message}</p>
              ) : null}
            </>
          ) : null}
        </div>

        <div className="space-y-3 rounded-xl border border-slate-200 bg-white p-4 lg:col-span-2">
          <div className="flex flex-wrap items-end gap-2">
            <div className="flex-1 min-w-[220px]">
              <label className="text-sm font-medium">Search domains</label>
              <input
                value={domainSearch}
                onChange={(e: ChangeEvent<HTMLInputElement>) =>
                  setDomainSearch(e.target.value)
                }
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-sm"
                placeholder="Search by domain or hosting type"
              />
            </div>
            <div className="min-w-[180px]">
              <label className="text-sm font-medium">Status filter</label>
              <select
                value={domainStatus}
                onChange={(e: ChangeEvent<HTMLSelectElement>) =>
                  setDomainStatus(e.target.value)
                }
                className="mt-1 w-full rounded border border-slate-300 px-3 py-2 text-sm"
              >
                <option value="all">All statuses</option>
                {domainStatusOptions.map((status) => (
                  <option key={status} value={status}>
                    {status}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="min-w-full text-left text-sm">
              <thead>
                <tr className="border-b border-slate-200 text-xs uppercase text-slate-500">
                  <th className="px-2 py-2">
                    <button
                      type="button"
                      onClick={() => toggleDomainSort("domain")}
                      className="inline-flex items-center gap-1"
                    >
                      Domain
                      <span
                        className={
                          domainSort.key === "domain"
                            ? "text-brand-700"
                            : "text-slate-400"
                        }
                      >
                        {getSortIndicator("domain")}
                      </span>
                    </button>
                  </th>
                  <th className="px-2 py-2">
                    <button
                      type="button"
                      onClick={() => toggleDomainSort("status")}
                      className="inline-flex items-center gap-1"
                    >
                      Subscription Status
                      <span
                        className={
                          domainSort.key === "status"
                            ? "text-brand-700"
                            : "text-slate-400"
                        }
                      >
                        {getSortIndicator("status")}
                      </span>
                    </button>
                  </th>
                  <th className="px-2 py-2">
                    <button
                      type="button"
                      onClick={() => toggleDomainSort("hosting")}
                      className="inline-flex items-center gap-1"
                    >
                      Hosting
                      <span
                        className={
                          domainSort.key === "hosting"
                            ? "text-brand-700"
                            : "text-slate-400"
                        }
                      >
                        {getSortIndicator("hosting")}
                      </span>
                    </button>
                  </th>
                  <th className="px-2 py-2">
                    <button
                      type="button"
                      onClick={() => toggleDomainSort("created")}
                      className="inline-flex items-center gap-1"
                    >
                      Created
                      <span
                        className={
                          domainSort.key === "created"
                            ? "text-brand-700"
                            : "text-slate-400"
                        }
                      >
                        {getSortIndicator("created")}
                      </span>
                    </button>
                  </th>
                  <th className="px-2 py-2">
                    <button
                      type="button"
                      onClick={() => toggleDomainSort("aliases")}
                      className="inline-flex items-center gap-1"
                    >
                      Aliases
                      <span
                        className={
                          domainSort.key === "aliases"
                            ? "text-brand-700"
                            : "text-slate-400"
                        }
                      >
                        {getSortIndicator("aliases")}
                      </span>
                    </button>
                  </th>
                  <th className="px-2 py-2">
                    <button
                      type="button"
                      onClick={() => toggleDomainSort("last_seen")}
                      className="inline-flex items-center gap-1"
                    >
                      Last seen
                      <span
                        className={
                          domainSort.key === "last_seen"
                            ? "text-brand-700"
                            : "text-slate-400"
                        }
                      >
                        {getSortIndicator("last_seen")}
                      </span>
                    </button>
                  </th>
                  <th className="px-2 py-2">
                    <button
                      type="button"
                      onClick={() => toggleDomainSort("actions")}
                      className="inline-flex items-center gap-1"
                    >
                      Actions
                      <span
                        className={
                          domainSort.key === "actions"
                            ? "text-brand-700"
                            : "text-slate-400"
                        }
                      >
                        {getSortIndicator("actions")}
                      </span>
                    </button>
                  </th>
                </tr>
              </thead>
              <tbody>
                {sortedDomains.length === 0 ? (
                  <tr>
                    <td className="px-2 py-3 text-slate-500" colSpan={7}>
                      No domains found.
                    </td>
                  </tr>
                ) : (
                  sortedDomains.map((domain) => (
                    <tr key={domain.id} className="border-b border-slate-100">
                      <td className="px-2 py-2 font-medium text-slate-900">
                        <a
                          href={getDomainHref(domain.domain_name)}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="underline decoration-slate-300 underline-offset-2 hover:text-brand-700"
                        >
                          {domain.domain_name}
                        </a>
                        {domain.subscription_id ? (
                          <p
                            className="text-xs font-normal text-slate-500"
                            title={`Subscription UUID: ${domain.subscription_id}`}
                          >
                            Subscription: {domain.subscription_name ?? "Linked"}
                          </p>
                        ) : (
                          <p
                            className="text-xs font-normal text-amber-700"
                            title="Run sync to link this domain to a subscription"
                          >
                            Subscription: Unlinked
                          </p>
                        )}
                      </td>
                      <td className="px-2 py-2">
                        <span
                          className={`inline-flex rounded px-2 py-0.5 text-xs font-medium ${getDomainStatusBadge(domain.status)}`}
                        >
                          {formatDomainStatusLabel(domain.status)}
                        </span>
                      </td>
                      <td className="px-2 py-2">
                        {domain.hosting_type ?? "unknown"}
                      </td>
                      <td className="px-2 py-2">
                        {formatDateTime(domain.source_created_at)}
                      </td>
                      <td className="px-2 py-2">{domain.aliases_count ?? 0}</td>
                      <td className="px-2 py-2">
                        {formatDateTime(domain.updated_at)}
                      </td>
                      <td className="px-2 py-2">
                        <div className="flex gap-2">
                          <button
                            onClick={() => onDomainAction(domain, "suspend")}
                            disabled={
                              loading ||
                              !domain.subscription_id ||
                              isDomainSuspended(domain.status)
                            }
                            title={
                              !domain.subscription_id
                                ? "Not linked to a subscription yet — run sync"
                                : undefined
                            }
                            className="rounded border border-rose-300 px-2 py-1 text-xs text-rose-700 disabled:cursor-not-allowed disabled:opacity-60"
                          >
                            Suspend
                          </button>
                          <button
                            onClick={() => onDomainAction(domain, "unsuspend")}
                            disabled={
                              loading ||
                              !domain.subscription_id ||
                              isDomainActive(domain.status)
                            }
                            title={
                              !domain.subscription_id
                                ? "Not linked to a subscription yet — run sync"
                                : undefined
                            }
                            className="rounded border border-emerald-300 px-2 py-1 text-xs text-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
                          >
                            Unsuspend
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </section>
  );
}
