'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { PageHeader } from '@bytelyst/dashboard-components';
import {
  Button,
  Badge,
  StatusBadge,
  StatusDot,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
  toast,
  type StatusTone,
} from '@/components/ui/Primitives';
import { useAuth } from '@/lib/auth-context';
import { useProduct } from '@/lib/product-context';
import { listItems, updateItemStatus, type TrackerItem } from '@/lib/tracker-client';

const COLUMNS: { key: string; label: string; color: string }[] = [
  { key: 'open', label: 'Open', color: 'border-t-green-500' },
  { key: 'in_progress', label: 'In Progress', color: 'border-t-yellow-500' },
  { key: 'done', label: 'Done', color: 'border-t-emerald-500' },
  { key: 'closed', label: 'Closed', color: 'border-t-gray-500' },
];

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',
};

export default function BoardPage() {
  const { token } = useAuth();
  const { productId } = useProduct();
  const [items, setItems] = useState<TrackerItem[]>([]);

  const fetchItems = useCallback(async () => {
    try {
      // Re-run when the selected product changes; apiFetch reads the product header from localStorage.
      void productId;
      const res = await listItems({ limit: '200' });
      setItems(res.items);
    } catch (err: unknown) {
      toast({
        type: 'error',
        title: 'Failed to load board',
        description: err instanceof Error ? err.message : undefined,
      });
    }
  }, [productId]);

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

  const handleStatusChange = async (itemId: string, newStatus: string) => {
    try {
      await updateItemStatus(itemId, newStatus);
      setItems(prev =>
        prev.map(i => (i.id === itemId ? { ...i, status: newStatus as TrackerItem['status'] } : i))
      );
    } catch (err: unknown) {
      toast({
        type: 'error',
        title: 'Failed to update status',
        description: err instanceof Error ? err.message : undefined,
      });
    }
  };

  return (
    <TooltipProvider>
      <div className="space-y-6">
        <PageHeader
          title="Board"
          breadcrumbs={[{ label: 'Dashboard', href: '/dashboard' }, { label: 'Board' }]}
        />
        <p className="-mt-4 text-sm text-muted-foreground">Kanban view of all items</p>

        <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
          {COLUMNS.map(col => {
            const colItems = items.filter(i => i.status === col.key);
            return (
              <div
                key={col.key}
                className={`rounded-xl border border-border border-t-4 ${col.color} bg-card p-3`}
              >
                <div className="mb-3 flex items-center justify-between">
                  <h3 className="text-sm font-semibold">{col.label}</h3>
                  <Badge variant="neutral">{colItems.length}</Badge>
                </div>

                <div className="space-y-2">
                  {colItems.map(item => (
                    <div
                      key={item.id}
                      className="rounded-lg border border-border bg-background p-3 shadow-sm transition-shadow hover:shadow-md"
                    >
                      <div className="mb-1 flex items-center gap-2">
                        <StatusDot tone={TYPE_TONE[item.type] ?? 'neutral'} />
                        <span className="text-xs text-muted-foreground">{item.type}</span>
                        <StatusBadge
                          tone={PRIORITY_TONE[item.priority] ?? 'neutral'}
                          className="ml-auto"
                        >
                          {item.priority}
                        </StatusBadge>
                      </div>

                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Link
                            href={`/dashboard/items/${item.id}`}
                            className="block truncate text-sm font-medium leading-tight hover:text-primary hover:underline"
                          >
                            {item.title}
                          </Link>
                        </TooltipTrigger>
                        <TooltipContent>{item.title}</TooltipContent>
                      </Tooltip>

                      <div className="mt-2 flex items-center gap-3 text-xs text-muted-foreground">
                        {item.voteCount > 0 && <span>{item.voteCount} votes</span>}
                        {item.commentCount > 0 && <span>{item.commentCount} comments</span>}
                      </div>

                      {/* Quick status move */}
                      <div className="mt-2 flex flex-wrap gap-1">
                        {COLUMNS.filter(c => c.key !== item.status).map(c => (
                          <Button
                            key={c.key}
                            variant="ghost"
                            size="sm"
                            onClick={() => handleStatusChange(item.id, c.key)}
                            className="h-auto px-1.5 py-0.5 text-[10px]"
                            title={`Move to ${c.label}`}
                          >
                            → {c.label}
                          </Button>
                        ))}
                      </div>
                    </div>
                  ))}

                  {colItems.length === 0 && (
                    <div className="py-8 text-center text-xs text-muted-foreground">No items</div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </TooltipProvider>
  );
}
