"use client";

import { useState } from "react";

import {
  type ColumnDef,
  type Table as TableType,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { CheckCircle2, GitBranch, Loader2 } from "lucide-react";
import { DataTable } from "@/components/tables/DataTable";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";

import type {
  ForgejoConnection,
  ForgejoConnectionValidationResponse,
} from "@/lib/api-forgejo";

interface ConnectionsTableProps {
  connections: ForgejoConnection[];
  isLoading: boolean;
  onEdit?: (connection: ForgejoConnection) => void;
  onDelete?: (connection: ForgejoConnection) => void;
  onValidate?: (
    connection: ForgejoConnection,
  ) => Promise<ForgejoConnectionValidationResponse>;
}

export function ForgejoConnectionsTable({
  connections,
  isLoading,
  onEdit,
  onDelete,
  onValidate,
}: ConnectionsTableProps) {
  // onEdit available for future use
  const _ = onEdit;
  const table = useReactTable({
    data: connections,
    columns: columns(onValidate),
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <DataTable
      table={table}
      isLoading={isLoading}
      emptyState={{
        icon: <GitBranch className="h-12 w-12" />,
        title: "No Git Project connections yet",
        description:
          "Connect a Git provider so Pipeline can track issues for Git Projects.",
        actionHref: "/git-projects/connections/new",
        actionLabel: "Add connection",
      }}
      rowActions={{
        getEditHref: (row) => `/git-projects/connections/${row.id}/edit`,
        onDelete: onDelete ?? undefined,
      }}
      tableClassName="min-w-[680px] w-full text-left text-sm"
    />
  );
}

const columns = (
  onValidate?: (
    connection: ForgejoConnection,
  ) => Promise<ForgejoConnectionValidationResponse>,
): ColumnDef<ForgejoConnection>[] => [
  {
    accessorKey: "name",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(false)}
          className="h-auto px-0 py-0 hover:bg-transparent hover:text-[color:var(--accent)]"
        >
          Name
          {column.getIsSorted() === "asc" && "↑"}
          {column.getIsSorted() === "desc" && "↓"}
        </Button>
      );
    },
    cell: ({ row }) => (
      <div className="min-w-0">
        <span className="block truncate font-medium text-strong">
          {row.original.name}
        </span>
        <span className="block truncate text-xs text-muted">
          {row.original.base_url}
        </span>
      </div>
    ),
  },
  {
    accessorKey: "status",
    header: "Status",
    cell: ({ row }) => {
      const isActive = row.original.active;
      return (
        <Badge variant={isActive ? "default" : "outline"}>
          {isActive ? "Active" : "Inactive"}
        </Badge>
      );
    },
  },
  {
    accessorKey: "hasToken",
    header: "Auth",
    cell: ({ row }) => {
      const hasToken = row.original.has_token;
      const tokenLastEight = row.original.token_last_eight;
      return (
        <div className="flex items-center gap-2">
          <Badge variant={hasToken ? "outline" : "default"}>
            {hasToken ? "Configured" : "Missing"}
          </Badge>
          {tokenLastEight && hasToken && (
            <span className="font-mono text-xs text-muted">
              ••••{tokenLastEight}
            </span>
          )}
        </div>
      );
    },
  },
  {
    id: "actions",
    cell: ({ row }) => (
      <ActionsCell connection={row.original} onValidate={onValidate} />
    ),
  },
];

function ActionsCell({
  connection,
  onValidate,
}: {
  connection: ForgejoConnection;
  onValidate?: (
    connection: ForgejoConnection,
  ) => Promise<ForgejoConnectionValidationResponse>;
}) {
  const [isValidateLoading, setIsValidateLoading] = useState(false);
  const [validateResult, setValidateResult] = useState<{
    ok: boolean;
    error_message?: string;
    response_time_ms?: number;
  } | null>(null);

  const handleValidate = async () => {
    if (!onValidate) return;
    setIsValidateLoading(true);
    try {
      const result = await onValidate(connection);
      setValidateResult({
        ok: result.status.ok,
        error_message: result.status.error_message ?? undefined,
        response_time_ms: result.response_time_ms,
      });
    } finally {
      setIsValidateLoading(false);
    }
  };

  return (
    <div className="flex items-center gap-2">
      {onValidate && (
        <Button
          variant="ghost"
          onClick={handleValidate}
          disabled={isValidateLoading}
          className="h-8 w-8 p-0"
          title="Validate connection"
        >
          {isValidateLoading ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : validateResult?.ok ? (
            <CheckCircle2 className="h-4 w-4 text-[color:var(--success)]" />
          ) : (
            <CheckCircle2 className="h-4 w-4" />
          )}
        </Button>
      )}
    </div>
  );
}

// Filter component
export function ConnectionsTableFilter({
  value,
  onChange,
}: {
  value: string;
  onChange: (value: string) => void;
}) {
  return (
    <Input
      placeholder="Filter connections..."
      value={value ?? ""}
      onChange={(e) => onChange(e.target.value)}
      className="h-8 w-[150px] lg:w-[250px]"
    />
  );
}

// Column toggle component
export function ConnectionsTableToggle({
  table,
}: {
  table: TableType<ForgejoConnection>;
}) {
  return (
    <div className="flex items-center gap-2">
      <div className="flex items-center gap-2">
        <span className="text-xs text-muted">Show:</span>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => table.toggleAllColumnsVisible()}
          className="h-8 px-2 py-1 text-xs"
        >
          All
        </Button>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => table.toggleAllColumnsVisible(false)}
          className="h-8 px-2 py-1 text-xs"
        >
          None
        </Button>
      </div>
      <div className="flex gap-1">
        {table
          .getAllColumns()
          .filter((column) => column.getCanHide())
          .map((column) => {
            return (
              <Button
                key={column.id}
                variant="ghost"
                size="sm"
                onClick={() => column.toggleVisibility(!column.getIsVisible())}
                className={cn(
                  "h-8 px-2 py-1 text-xs",
                  column.getIsVisible()
                    ? "bg-[color:var(--surface-strong)] text-strong"
                    : "text-muted",
                )}
              >
                {column.id}
              </Button>
            );
          })}
      </div>
    </div>
  );
}
