'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
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;
}

const TAGS_QUERY_KEY = ['admin', 'tags'] as const;

export function TagList() {
  const queryClient = useQueryClient();
  const [formOpen, setFormOpen] = useState(false);
  const [editingTag, setEditingTag] = useState<Tag | null>(null);

  const { data: tags = [], isLoading: loading } = useQuery<Tag[]>({
    queryKey: TAGS_QUERY_KEY,
    queryFn: () => apiFetch<{ data: Tag[] }>('/api/v1/tags').then((r) => r.data),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => apiFetch(`/api/v1/tags/${id}`, { method: 'DELETE' }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: TAGS_QUERY_KEY }),
  });

  const fetchTags = () => queryClient.invalidateQueries({ queryKey: TAGS_QUERY_KEY });

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

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

  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" aria-hidden />
            <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" aria-hidden />
                <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={() => deleteMutation.mutate(row.original.id)}
            loading={deleteMutation.isPending && deleteMutation.variables === 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" aria-hidden />
            New Tag
          </Button>
        }
      />

      <DataTable
        columns={columns}
        data={tags}
        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="flex min-w-0 items-center gap-2">
              <span
                aria-hidden
                className="inline-block h-3 w-3 shrink-0 rounded-full"
                style={{ backgroundColor: original.color }}
              />
              <div className="min-w-0">
                <p className="truncate text-sm font-semibold text-foreground">{original.name}</p>
                <p className="mt-0.5 text-xs text-muted-foreground">
                  <span className="font-mono">{original.color}</span>
                  {' · '}
                  Created {new Date(original.createdAt).toLocaleDateString()}
                </p>
              </div>
            </div>
            <div className="flex shrink-0 items-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleEditTag(original)}
                aria-label={`Edit ${original.name}`}
              >
                <Pencil className="h-4 w-4" aria-hidden />
              </Button>
              <ConfirmationDialog
                trigger={
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-destructive hover:text-destructive"
                    aria-label={`Delete ${original.name}`}
                  >
                    <Trash2 className="h-4 w-4" aria-hidden />
                  </Button>
                }
                title="Delete Tag"
                description={`Are you sure you want to delete "${original.name}"? This action cannot be undone.`}
                confirmLabel="Delete"
                onConfirm={() => deleteMutation.mutate(original.id)}
                loading={deleteMutation.isPending && deleteMutation.variables === original.id}
              />
            </div>
          </div>
        )}
        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>
  );
}
