'use client';

import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { type ColumnDef } from '@tanstack/react-table';
import { Pencil, Plus } from 'lucide-react';

import { DataTable } from '@/components/shared/data-table';
import { PageHeader } from '@/components/shared/page-header';
import { Button } from '@/components/ui/button';
import { StatusPill } from '@/components/ui/status-pill';
import { apiFetch } from '@/lib/api/client';
import { PortForm } from './port-form';

interface PortRow {
  id: string;
  name: string;
  slug: string;
  logoUrl: string | null;
  primaryColor: string | null;
  defaultCurrency: string;
  timezone: string;
  isActive: boolean;
  settings: Record<string, unknown>;
  createdAt: string;
}

const PORTS_QUERY_KEY = ['admin', 'ports'] as const;

export function PortList() {
  const queryClient = useQueryClient();
  const [formOpen, setFormOpen] = useState(false);
  const [editingPort, setEditingPort] = useState<PortRow | null>(null);

  const { data: ports = [], isLoading: loading } = useQuery<PortRow[]>({
    queryKey: PORTS_QUERY_KEY,
    queryFn: () => apiFetch<{ data: PortRow[] }>('/api/v1/admin/ports').then((r) => r.data),
  });

  const fetchPorts = () => queryClient.invalidateQueries({ queryKey: PORTS_QUERY_KEY });

  function handleNewPort() {
    setEditingPort(null);
    setFormOpen(true);
  }

  function handleEditPort(port: PortRow) {
    setEditingPort(port);
    setFormOpen(true);
  }

  const columns: ColumnDef<PortRow, unknown>[] = [
    {
      accessorKey: 'name',
      header: 'Name',
      cell: ({ row }) => (
        <div className="flex items-center gap-2">
          {row.original.primaryColor && (
            <span
              className="inline-block h-3 w-3 rounded-full"
              style={{ backgroundColor: row.original.primaryColor }}
            />
          )}
          <span className="font-medium">{row.original.name}</span>
        </div>
      ),
    },
    {
      accessorKey: 'slug',
      header: 'Slug',
      cell: ({ row }) => (
        <code className="text-xs bg-muted px-1.5 py-0.5 rounded">{row.original.slug}</code>
      ),
    },
    {
      accessorKey: 'defaultCurrency',
      header: 'Currency',
    },
    {
      accessorKey: 'timezone',
      header: 'Timezone',
    },
    {
      accessorKey: 'isActive',
      header: 'Status',
      cell: ({ row }) =>
        row.original.isActive ? (
          <StatusPill status="enabled">Active</StatusPill>
        ) : (
          <StatusPill status="disabled">Inactive</StatusPill>
        ),
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => (
        <Button variant="ghost" size="sm" onClick={() => handleEditPort(row.original)}>
          <Pencil className="h-4 w-4" aria-hidden />
          <span className="sr-only">Edit</span>
        </Button>
      ),
      enableSorting: false,
      size: 60,
    },
  ];

  return (
    <div>
      <PageHeader
        title="Port Management"
        description="Manage marina ports and their configuration"
        actions={
          <Button onClick={handleNewPort}>
            <Plus className="mr-1.5 h-4 w-4" aria-hidden />
            New Port
          </Button>
        }
      />

      <DataTable
        columns={columns}
        data={ports}
        isLoading={loading}
        getRowId={(row) => row.id}
        cardRender={({ original }) => (
          <div className="flex items-start justify-between gap-3 rounded-xl border border-border bg-card p-4 shadow-sm">
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-2">
                {original.primaryColor ? (
                  <span
                    aria-hidden
                    className="inline-block h-3 w-3 shrink-0 rounded-full"
                    style={{ backgroundColor: original.primaryColor }}
                  />
                ) : null}
                <p className="truncate text-sm font-semibold text-foreground">{original.name}</p>
                {original.isActive ? (
                  <StatusPill status="enabled">Active</StatusPill>
                ) : (
                  <StatusPill status="disabled">Inactive</StatusPill>
                )}
              </div>
              <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
                <code className="rounded bg-muted px-1.5 py-0.5">{original.slug}</code>
                <span>{original.defaultCurrency}</span>
                <span aria-hidden>·</span>
                <span>{original.timezone}</span>
              </div>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleEditPort(original)}
              aria-label={`Edit ${original.name}`}
              className="shrink-0"
            >
              <Pencil className="h-4 w-4" aria-hidden />
            </Button>
          </div>
        )}
        emptyState={
          <div className="text-center py-8">
            <p className="text-muted-foreground">No ports configured.</p>
          </div>
        }
      />

      <PortForm
        open={formOpen}
        onOpenChange={setFormOpen}
        port={editingPort}
        onSuccess={fetchPorts}
      />
    </div>
  );
}
