"use client"

import { useMemo, type ReactNode } from "react"
import {
  type ColumnDef,
  getCoreRowModel,
  getExpandedRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table"
import type { CertStatus, Server } from "@/lib/data"
import type { CertificateDto } from "@mmapp/contracts/certificates"
import { Flag } from "@/components/flag"
import { cn } from "@/lib/utils"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import {
  DATA_GRID_CELL_PAD,
  DATA_GRID_CELL_PAD_FIRST,
  DATA_GRID_CELL_PAD_LAST,
} from "@/components/data-grids/shared/data-grid-layout"
import { DataGridSortHeader } from "@/components/data-grids/shared/data-grid-sort-header"
import {
  CertificateExpandedDetail,
  daysLeftBar,
} from "@/components/data-grids/certificate-expanded-detail"
import { EmptyState } from "@/components/empty-state"
import {
  BadgeCheckIcon,
  ChevronDownIcon,
  ChevronRightIcon,
  ServerIcon,
  ShieldAlertIcon,
  ShieldCheckIcon,
  ShieldOffIcon,
} from "lucide-react"

const STATUS_CONFIG: Record<
  CertStatus,
  { label: string; icon: ReactNode; badge: string; row: string }
> = {
  valid: {
    label: "Действителен",
    icon: <BadgeCheckIcon className="size-4 text-emerald-500" />,
    badge: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20",
    row: "",
  },
  expired: {
    label: "Истёк",
    icon: <ShieldOffIcon className="size-4 text-red-500" />,
    badge: "bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/20",
    row: "bg-red-500/5",
  },
  revoked: {
    label: "Отозван",
    icon: <ShieldAlertIcon className="size-4 text-amber-500" />,
    badge: "bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",
    row: "bg-amber-500/5",
  },
}

function daysLeftColor(days: number): string {
  if (days < 0) return "text-red-500"
  if (days <= 7) return "text-red-500"
  if (days <= 30) return "text-amber-500"
  return "text-emerald-600 dark:text-emerald-400"
}

function CertDaysCell({ cert }: { cert: CertificateDto }) {
  const pct = daysLeftBar(cert.daysLeft)
  return (
    <>
      <div className="flex items-center justify-between text-xs mb-1">
        <span className={cn("font-mono font-medium", daysLeftColor(cert.daysLeft))}>
          {cert.daysLeft < 0 ? `Истёк ${-cert.daysLeft}д назад` : `${cert.daysLeft}д осталось`}
        </span>
        <span className="text-muted-foreground text-[10px]">{cert.validUntil}</span>
      </div>
      <div className="h-1.5 bg-muted rounded-full overflow-hidden">
        <div
          className={cn(
            "h-full rounded-full",
            cert.daysLeft < 0 || cert.daysLeft <= 7
              ? "bg-red-500"
              : cert.daysLeft <= 30
                ? "bg-amber-500"
                : "bg-emerald-500",
          )}
          style={{ width: `${pct}%` }}
        />
      </div>
    </>
  )
}

interface CertificatesDataGridProps {
  certificates: CertificateDto[]
  serverMap: Map<string, Server>
  isLoading?: boolean
}

function CertificatesDataGrid({ certificates, serverMap, isLoading }: CertificatesDataGridProps) {
  const columns = useMemo<ColumnDef<CertificateDto>[]>(
    () => [
      {
        id: "name",
        accessorKey: "name",
        header: ({ column }) => (
          <DataGridSortHeader column={column} title="Сертификат" className="ml-1" />
        ),
        cell: ({ row }) => {
          const cert = row.original
          const cfg = STATUS_CONFIG[cert.status]
          const expanded = row.getIsExpanded()
          return (
            <div className="flex items-start gap-2 min-w-0">
              {expanded ? (
                <ChevronDownIcon className="size-3.5 mt-0.5 shrink-0 text-muted-foreground" />
              ) : (
                <ChevronRightIcon className="size-3.5 mt-0.5 shrink-0 text-muted-foreground/40" />
              )}
              <div className="min-w-0">
                <div className="flex items-center gap-2 min-w-0">
                  <span className="shrink-0">{cfg.icon}</span>
                  <span className="font-medium text-sm truncate" title={cert.name}>
                    {cert.name}
                  </span>
                </div>
                <p className="text-xs text-muted-foreground font-mono mt-0.5 truncate" title={cert.commonName}>
                  {cert.commonName}
                </p>
              </div>
            </div>
          )
        },
        meta: {
          headerTitle: "Сертификат",
          headerClassName: DATA_GRID_CELL_PAD_FIRST,
          cellClassName: DATA_GRID_CELL_PAD_FIRST,
          expandedContent: (row: CertificateDto) => <CertificateExpandedDetail cert={row} />,
        },
      },
      {
        id: "server",
        accessorKey: "serverId",
        header: ({ column }) => <DataGridSortHeader column={column} title="Сервер" />,
        cell: ({ row }) => {
          const cert = row.original
          const server = serverMap.get(cert.serverId)
          return server ? (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground min-w-0">
              <Flag code={server.country} size={12} />
              <span className="font-mono truncate">{server.name}</span>
            </div>
          ) : (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground min-w-0">
              <ServerIcon className="size-3.5" />
              <span className="font-mono truncate">{cert.serverName ?? cert.serverId}</span>
            </div>
          )
        },
        meta: {
          headerTitle: "Сервер",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "issuedBy",
        accessorKey: "issuedBy",
        header: ({ column }) => <DataGridSortHeader column={column} title="Издатель" />,
        cell: ({ row }) => (
          <p className="text-xs text-muted-foreground truncate min-w-0" title={row.original.issuedBy}>
            {row.original.issuedBy}
          </p>
        ),
        meta: {
          headerTitle: "Издатель",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "daysLeft",
        accessorKey: "daysLeft",
        header: ({ column }) => <DataGridSortHeader column={column} title="Срок" />,
        cell: ({ row }) => (
          <div className="min-w-0">
            <CertDaysCell cert={row.original} />
          </div>
        ),
        meta: {
          headerTitle: "Срок",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "usage",
        accessorKey: "usage",
        header: () => <span className="text-xs font-medium text-muted-foreground">Использование</span>,
        enableSorting: false,
        cell: ({ row }) => (
          <div className="flex flex-wrap gap-1 min-w-0 overflow-hidden">
            {row.original.usage.map((u) => (
              <span
                key={u}
                className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground border"
              >
                {u}
              </span>
            ))}
          </div>
        ),
        meta: {
          headerTitle: "Использование",
          headerClassName: DATA_GRID_CELL_PAD,
          cellClassName: DATA_GRID_CELL_PAD,
        },
      },
      {
        id: "status",
        accessorKey: "status",
        header: ({ column }) => <DataGridSortHeader column={column} title="Статус" />,
        cell: ({ row }) => {
          const cfg = STATUS_CONFIG[row.original.status]
          return (
            <span
              className={cn(
                "text-[11px] font-mono px-2 py-0.5 rounded border whitespace-nowrap",
                cfg.badge,
              )}
            >
              {cfg.label}
            </span>
          )
        },
        meta: {
          headerTitle: "Статус",
          headerClassName: DATA_GRID_CELL_PAD_LAST,
          cellClassName: DATA_GRID_CELL_PAD_LAST,
        },
      },
    ],
    [serverMap],
  )

  const table = useReactTable({
    data: certificates,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getExpandedRowModel: getExpandedRowModel(),
    getRowId: (row) => row.id,
    getRowCanExpand: () => true,
  })

  if (!isLoading && certificates.length === 0) {
    return (
      <EmptyState
        icon={<ShieldCheckIcon className="size-4" />}
        title="Нет сертификатов"
        description="Выпустите или импортируйте сертификат"
        className="border-0 py-12"
      />
    )
  }

  return (
    <DataGridShell
      table={table}
      recordCount={certificates.length}
      isLoading={isLoading}
      loadingMode="skeleton"
      onRowClick={(row) => table.getRow(row.id).toggleExpanded()}
    />
  )
}

export { CertificatesDataGrid, STATUS_CONFIG, type CertificatesDataGridProps }
