'use client';

import { useState, useEffect, useCallback } from 'react';
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 { Badge } from '@/components/ui/badge';
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;
}

export function PortList() {
  const [ports, setPorts] = useState<PortRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [formOpen, setFormOpen] = useState(false);
  const [editingPort, setEditingPort] = useState<PortRow | null>(null);

  const fetchPorts = useCallback(async () => {
    setLoading(true);
    try {
      const res = await apiFetch<{ data: PortRow[] }>('/api/v1/admin/ports');
      setPorts(res.data);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void fetchPorts();
  }, [fetchPorts]);

  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 ? (
          <Badge variant="default" className="bg-green-600">
            Active
          </Badge>
        ) : (
          <Badge variant="destructive">Inactive</Badge>
        ),
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => (
        <Button variant="ghost" size="sm" onClick={() => handleEditPort(row.original)}>
          <Pencil className="h-4 w-4" />
          <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" />
            New Port
          </Button>
        }
      />

      <DataTable
        columns={columns}
        data={ports}
        isLoading={loading}
        getRowId={(row) => row.id}
        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>
  );
}
