'use client';

import { useEffect, useState, useCallback, useMemo } from 'react';
import Link from 'next/link';
import { DataTable, type ColumnDef } from '@bytelyst/data-table';
import { PageHeader, LoadingSpinner } from '@bytelyst/dashboard-components';
import { Reveal } from '@bytelyst/motion';
import {
  Button,
  Input,
  Select,
  Textarea,
  Field,
  FieldLabel,
  Modal,
  ConfirmDialog,
  StatusBadge,
  toast,
  type StatusTone,
} from '@/components/ui/Primitives';
import { useAuth } from '@/lib/auth-context';
import { useProduct } from '@/lib/product-context';
import { listItems, createItem, deleteItem, type TrackerItem } from '@/lib/tracker-client';

const TYPE_TONE: Record<string, StatusTone> = {
  bug: 'danger',
  feature: 'info',
  task: 'warning',
};

const PRIORITY_TONE: Record<string, StatusTone> = {
  critical: 'danger',
  high: 'warning',
  medium: 'neutral',
  low: 'success',
};

const STATUS_TONE: Record<string, StatusTone> = {
  open: 'success',
  in_progress: 'warning',
  done: 'success',
  closed: 'neutral',
  wont_fix: 'neutral',
};

export default function ItemsListPage() {
  const { token } = useAuth();
  const { productId } = useProduct();
  const [items, setItems] = useState<TrackerItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  // Filters
  const [typeFilter, setTypeFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [priorityFilter, setPriorityFilter] = useState('');
  const [search, setSearch] = useState('');

  // Create modal
  const [showCreate, setShowCreate] = useState(false);
  const [newTitle, setNewTitle] = useState('');
  const [newType, setNewType] = useState<'bug' | 'feature' | 'task'>('bug');
  const [newPriority, setNewPriority] = useState<'critical' | 'high' | 'medium' | 'low'>('medium');
  const [newDescription, setNewDescription] = useState('');

  // Delete confirmation
  const [deleteId, setDeleteId] = useState<string | null>(null);

  const fetchItems = useCallback(async () => {
    setLoading(true);
    try {
      // Re-run when the selected product changes; apiFetch reads the product header from localStorage.
      void productId;
      const params: Record<string, string> = {};
      if (typeFilter) params.type = typeFilter;
      if (statusFilter) params.status = statusFilter;
      if (priorityFilter) params.priority = priorityFilter;
      if (search) params.q = search;
      const res = await listItems(params);
      setItems(res.items);
      setTotal(res.total);
    } catch (err: unknown) {
      toast({
        type: 'error',
        title: 'Failed to load items',
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setLoading(false);
    }
  }, [typeFilter, statusFilter, priorityFilter, search, productId]);

  useEffect(() => {
    if (token) fetchItems();
  }, [token, fetchItems]);

  // The ⌘K "New item" command navigates here with ?new=1 — open the create
  // modal and strip the param so a refresh doesn't reopen it (UX-5).
  useEffect(() => {
    if (typeof window === 'undefined') return;
    const params = new URLSearchParams(window.location.search);
    if (params.get('new') === '1') {
      setShowCreate(true);
      params.delete('new');
      const qs = params.toString();
      window.history.replaceState(null, '', window.location.pathname + (qs ? `?${qs}` : ''));
    }
  }, []);

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await createItem({
        type: newType,
        priority: newPriority,
        title: newTitle,
        description: newDescription,
      });
      setShowCreate(false);
      setNewTitle('');
      setNewDescription('');
      toast({ type: 'success', title: 'Item created' });
      fetchItems();
    } catch (err: unknown) {
      toast({
        type: 'error',
        title: 'Failed to create item',
        description: err instanceof Error ? err.message : undefined,
      });
    }
  };

  const handleDelete = useCallback((id: string) => setDeleteId(id), []);

  const confirmDelete = useCallback(async () => {
    if (!deleteId) return;
    try {
      await deleteItem(deleteId);
      setDeleteId(null);
      toast({ type: 'success', title: 'Item deleted' });
      fetchItems();
    } catch (err: unknown) {
      setDeleteId(null);
      toast({
        type: 'error',
        title: 'Failed to delete',
        description: err instanceof Error ? err.message : undefined,
      });
    }
  }, [deleteId, fetchItems]);

  const columns = useMemo<ColumnDef<TrackerItem, unknown>[]>(
    () => [
      {
        id: 'title',
        accessorKey: 'title',
        header: 'Title',
        cell: ({ row }) => {
          const item = row.original;
          return (
            <div>
              <Link
                href={`/dashboard/items/${item.id}`}
                className="font-medium text-foreground hover:text-primary hover:underline"
              >
                {item.title}
              </Link>
              {item.labels.length > 0 && (
                <div className="mt-1 flex gap-1">
                  {item.labels.map(l => (
                    <span
                      key={l}
                      className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground"
                    >
                      {l}
                    </span>
                  ))}
                </div>
              )}
            </div>
          );
        },
      },
      {
        id: 'type',
        accessorKey: 'type',
        header: 'Type',
        cell: ({ row }) => (
          <StatusBadge tone={TYPE_TONE[row.original.type] ?? 'neutral'}>
            {row.original.type}
          </StatusBadge>
        ),
      },
      {
        id: 'status',
        accessorKey: 'status',
        header: 'Status',
        cell: ({ row }) => (
          <StatusBadge tone={STATUS_TONE[row.original.status] ?? 'neutral'} dot>
            {row.original.status.replace(/_/g, ' ')}
          </StatusBadge>
        ),
      },
      {
        id: 'priority',
        accessorKey: 'priority',
        header: 'Priority',
        cell: ({ row }) => (
          <StatusBadge tone={PRIORITY_TONE[row.original.priority] ?? 'neutral'}>
            {row.original.priority}
          </StatusBadge>
        ),
      },
      { id: 'voteCount', accessorKey: 'voteCount', header: 'Votes' },
      { id: 'commentCount', accessorKey: 'commentCount', header: 'Comments' },
      {
        id: 'actions',
        header: 'Actions',
        enableSorting: false,
        cell: ({ row }) => (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleDelete(row.original.id)}
            className="text-muted-foreground hover:text-destructive"
          >
            Delete
          </Button>
        ),
      },
    ],
    [handleDelete]
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <PageHeader
        title="Items"
        breadcrumbs={[{ label: 'Dashboard', href: '/dashboard' }, { label: 'Items' }]}
        actions={<Button onClick={() => setShowCreate(true)}>+ New Item</Button>}
      />
      <p className="-mt-4 text-sm text-muted-foreground">{total} items total</p>

      {/* Filters */}
      <div className="flex flex-wrap gap-3">
        <Input
          type="text"
          placeholder="Search..."
          aria-label="Search items"
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
        <Select
          aria-label="Filter by type"
          value={typeFilter}
          onChange={e => setTypeFilter(e.target.value)}
          options={[
            { value: '', label: 'All types' },
            { value: 'bug', label: 'Bug' },
            { value: 'feature', label: 'Feature' },
            { value: 'task', label: 'Task' },
          ]}
        />
        <Select
          aria-label="Filter by status"
          value={statusFilter}
          onChange={e => setStatusFilter(e.target.value)}
          options={[
            { value: '', label: 'All statuses' },
            { value: 'open', label: 'Open' },
            { value: 'in_progress', label: 'In Progress' },
            { value: 'done', label: 'Done' },
            { value: 'closed', label: 'Closed' },
            { value: 'wont_fix', label: "Won't Fix" },
          ]}
        />
        <Select
          aria-label="Filter by priority"
          value={priorityFilter}
          onChange={e => setPriorityFilter(e.target.value)}
          options={[
            { value: '', label: 'All priorities' },
            { value: 'critical', label: 'Critical' },
            { value: 'high', label: 'High' },
            { value: 'medium', label: 'Medium' },
            { value: 'low', label: 'Low' },
          ]}
        />
      </div>

      {/* Items table — @bytelyst/data-table (Wave 9.C.9) */}
      {loading ? (
        <div className="flex justify-center py-10">
          <LoadingSpinner />
        </div>
      ) : (
        <Reveal>
          <DataTable
            ariaLabel="Tracker items"
            columns={columns}
            data={items}
            getRowId={item => item.id}
            enableFilter={false}
            enableSorting
            enablePagination
            pageSize={15}
            emptyState="No items found. Create one to get started."
          />
        </Reveal>
      )}

      {/* Create modal */}
      <Modal open={showCreate} onOpenChange={setShowCreate} title="New Item">
        <form onSubmit={handleCreate} className="space-y-4">
          <Input
            label="Title"
            type="text"
            required
            value={newTitle}
            onChange={e => setNewTitle(e.target.value)}
          />
          <div className="grid grid-cols-2 gap-4">
            <Select
              label="Type"
              value={newType}
              onChange={e => setNewType(e.target.value as 'bug' | 'feature' | 'task')}
              options={[
                { value: 'bug', label: 'Bug' },
                { value: 'feature', label: 'Feature' },
                { value: 'task', label: 'Task' },
              ]}
            />
            <Select
              label="Priority"
              value={newPriority}
              onChange={e =>
                setNewPriority(e.target.value as 'critical' | 'high' | 'medium' | 'low')
              }
              options={[
                { value: 'critical', label: 'Critical' },
                { value: 'high', label: 'High' },
                { value: 'medium', label: 'Medium' },
                { value: 'low', label: 'Low' },
              ]}
            />
          </div>
          <Field>
            <FieldLabel htmlFor="new-item-description">Description</FieldLabel>
            <Textarea
              id="new-item-description"
              value={newDescription}
              onChange={e => setNewDescription(e.target.value)}
              rows={4}
            />
          </Field>
          <div className="flex justify-end gap-3">
            <Button type="button" variant="ghost" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
            <Button type="submit">Create</Button>
          </div>
        </form>
      </Modal>

      {/* Delete confirmation */}
      <ConfirmDialog
        open={deleteId !== null}
        onOpenChange={open => {
          if (!open) setDeleteId(null);
        }}
        title="Delete item"
        description="Delete this item? This action cannot be undone."
        confirmLabel="Delete"
        onConfirm={confirmDelete}
      />
    </div>
  );
}
