"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { RefreshCw } from "lucide-react";
import { PageHeader } from "@/components/layout/PageHeader";
import { EmptyState } from "@/components/layout/EmptyState";
import { ErrorState } from "@/components/layout/ErrorState";
import { StatusBadge } from "@/components/ui/status-badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { apiFetch, errorMessageForUi } from "@/lib/api";
import {
  connectionBadgeVariant,
  connectionStatusIndicator,
  formatConnectionStatus,
  formatDateTime,
} from "@/lib/geotab-display";

type Account = {
  id: string;
  tenantId: string;
  databaseName: string;
  server?: string | null;
  connectionStatus: string;
  isConnected: boolean;
  addinStatus?: string | null;
  lastCheckedAt?: string | null;
  lastSyncAt?: string | null;
  lastError?: string | null;
  vehicleCount?: number;
  tenant?: { id: string; name: string; slug: string };
};

type ActionResult = { message: string };

export default function IntegrationsPage() {
  const [rows, setRows] = useState<Account[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [actionMessage, setActionMessage] = useState<string | null>(null);
  const [actionError, setActionError] = useState<string | null>(null);

  const load = useCallback(async () => {
    const data = await apiFetch<Account[]>("/geotab/accounts");
    setRows(data);
  }, []);

  useEffect(() => {
    setLoading(true);
    load()
      .catch((err) => setError(errorMessageForUi(err, "Failed")))
      .finally(() => setLoading(false));
  }, [load]);

  async function runCheck(accountId: string) {
    setBusyId(accountId);
    setActionError(null);
    setActionMessage(null);
    try {
      const result = await apiFetch<ActionResult>(
        `/geotab/accounts/${accountId}/check-connection`,
        { method: "POST" },
      );
      setActionMessage(result.message);
      await load();
    } catch (err) {
      const message = errorMessageForUi(err, "Check failed");
      if (message) setActionError(message);
    } finally {
      setBusyId(null);
    }
  }

  async function runSync(accountId: string) {
    setBusyId(accountId);
    setActionError(null);
    setActionMessage(null);
    try {
      const result = await apiFetch<ActionResult>(
        `/geotab/accounts/${accountId}/sync-vehicles`,
        { method: "POST" },
      );
      setActionMessage(result.message);
      await load();
    } catch (err) {
      const message = errorMessageForUi(err, "Sync failed");
      if (message) setActionError(message);
    } finally {
      setBusyId(null);
    }
  }

  return (
    <>
      <PageHeader
        title="MyGeotab accounts"
        description="Integration records only. Credentials and secrets are never displayed. Live MyGeotab testing is out of scope."
      />

      {error ? <ErrorState message={error} /> : null}

      {actionError ? (
        <Alert variant="destructive" className="mb-4">
          <AlertTitle>Action failed</AlertTitle>
          <AlertDescription>{actionError}</AlertDescription>
        </Alert>
      ) : null}

      {actionMessage ? (
        <Alert className="mb-4">
          <AlertTitle>Success</AlertTitle>
          <AlertDescription>{actionMessage}</AlertDescription>
        </Alert>
      ) : null}

      {loading ? (
        <Skeleton className="h-48 w-full" />
      ) : !rows.length ? (
        <EmptyState title="No integrations" description="No Geotab account records found." />
      ) : (
        <div className="overflow-hidden rounded-lg border bg-card">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Customer</TableHead>
                <TableHead>Database</TableHead>
                <TableHead className="hidden md:table-cell">Status</TableHead>
                <TableHead className="hidden lg:table-cell">Last check</TableHead>
                <TableHead className="hidden lg:table-cell">Last sync</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.map((a) => (
                <TableRow key={a.id}>
                  <TableCell className="font-medium">
                    {a.tenant ? (
                      <Link
                        href={`/admin/customers/${a.tenant.id}`}
                        className="underline-offset-4 hover:underline"
                      >
                        {a.tenant.name}
                      </Link>
                    ) : (
                      "—"
                    )}
                  </TableCell>
                  <TableCell>
                    <div>{a.databaseName}</div>
                    <div className="text-xs text-muted-foreground">{a.server || "—"}</div>
                  </TableCell>
                  <TableCell className="hidden md:table-cell">
                    <StatusBadge
                      variant={connectionBadgeVariant(a.connectionStatus)}
                      indicator={connectionStatusIndicator(a.connectionStatus)}
                    >
                      {formatConnectionStatus(a.connectionStatus)}
                    </StatusBadge>
                  </TableCell>
                  <TableCell className="hidden text-muted-foreground lg:table-cell">
                    {formatDateTime(a.lastCheckedAt)}
                  </TableCell>
                  <TableCell className="hidden text-muted-foreground lg:table-cell">
                    {formatDateTime(a.lastSyncAt)}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        disabled={busyId !== null}
                        onClick={() => void runCheck(a.id)}
                      >
                        <RefreshCw
                          className={`mr-1 h-3.5 w-3.5 ${busyId === a.id ? "animate-spin" : ""}`}
                        />
                        Check
                      </Button>
                      <Button
                        size="sm"
                        disabled={busyId !== null}
                        onClick={() => void runSync(a.id)}
                      >
                        Sync
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}
    </>
  );
}
