'use client';

import { useState, useEffect, useCallback } from 'react';
import { type ColumnDef } from '@tanstack/react-table';
import { Pencil, Trash2, Plus } from 'lucide-react';

import { DataTable } from '@/components/shared/data-table';
import { PageHeader } from '@/components/shared/page-header';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { apiFetch } from '@/lib/api/client';
import { TagForm } from './tag-form';

interface Tag {
  id: string;
  name: string;
  color: string;
  createdAt: string;
}

export function TagList() {
  const [tags, setTags] = useState<Tag[]>([]);
  const [loading, setLoading] = useState(true);
  const [formOpen, setFormOpen] = useState(false);
  const [editingTag, setEditingTag] = useState<Tag | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const fetchTags = useCallback(async () => {
    setLoading(true);
    try {
      const res = await apiFetch<{ data: Tag[] }>('/api/v1/tags');
      setTags(res.data);
    } finally {
      setLoading(false);
    }
  }, []);

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

  function handleNewTag() {
    setEditingTag(null);
    setFormOpen(true);
  }

  function handleEditTag(tag: Tag) {
    setEditingTag(tag);
    setFormOpen(true);
  }

  async function handleDeleteTag(id: string) {
    setDeletingId(id);
    try {
      await apiFetch(`/api/v1/tags/${id}`, { method: 'DELETE' });
      await fetchTags();
    } finally {
      setDeletingId(null);
    }
  }

  const columns: ColumnDef<Tag, unknown>[] = [
    {
      accessorKey: 'name',
      header: 'Name',
      cell: ({ row }) => (
        <div className="flex items-center gap-2">
          <span
            className="inline-block h-3 w-3 rounded-full"
            style={{ backgroundColor: row.original.color }}
          />
          <span className="font-medium">{row.original.name}</span>
        </div>
      ),
    },
    {
      accessorKey: 'color',
      header: 'Color',
      cell: ({ row }) => (
        <Badge
          variant="outline"
          className="font-mono text-xs"
          style={{ borderColor: row.original.color, color: row.original.color }}
        >
          {row.original.color}
        </Badge>
      ),
    },
    {
      accessorKey: 'createdAt',
      header: 'Created',
      cell: ({ row }) =>
        new Date(row.original.createdAt).toLocaleDateString(),
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => (
        <div className="flex items-center justify-end gap-1">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleEditTag(row.original)}
          >
            <Pencil className="h-4 w-4" />
            <span className="sr-only">Edit</span>
          </Button>
          <ConfirmationDialog
            trigger={
              <Button
                variant="ghost"
                size="sm"
                className="text-destructive hover:text-destructive"
              >
                <Trash2 className="h-4 w-4" />
                <span className="sr-only">Delete</span>
              </Button>
            }
            title="Delete Tag"
            description={`Are you sure you want to delete "${row.original.name}"? This action cannot be undone.`}
            confirmLabel="Delete"
            onConfirm={() => handleDeleteTag(row.original.id)}
            loading={deletingId === row.original.id}
          />
        </div>
      ),
      enableSorting: false,
      size: 80,
    },
  ];

  return (
    <div>
      <PageHeader
        title="Tag Management"
        description="Manage tags used across clients and records"
        actions={
          <Button onClick={handleNewTag}>
            <Plus className="mr-1.5 h-4 w-4" />
            New Tag
          </Button>
        }
      />

      <DataTable
        columns={columns}
        data={tags}
        isLoading={loading}
        getRowId={(row) => row.id}
        emptyState={
          <div className="text-center py-8">
            <p className="text-muted-foreground">No tags yet.</p>
            <Button variant="link" onClick={handleNewTag} className="mt-2">
              Create your first tag
            </Button>
          </div>
        }
      />

      <TagForm
        open={formOpen}
        onOpenChange={setFormOpen}
        tag={editingTag}
        onSuccess={fetchTags}
      />
    </div>
  );
}
