'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { useAuth } from '@/lib/auth-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_DOT: Record<string, string> = {
  bug: 'bg-red-500',
  feature: 'bg-blue-500',
  task: 'bg-amber-500',
};

const PRIORITY_LABEL: Record<string, string> = {
  critical: 'text-red-600 dark:text-red-400',
  high: 'text-orange-600 dark:text-orange-400',
  medium: 'text-yellow-600 dark:text-yellow-400',
  low: 'text-green-600 dark:text-green-400',
};

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

  const fetchItems = useCallback(async () => {
    try {
      const res = await listItems({ limit: '200' });
      setItems(res.items);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to load');
    }
  }, []);

  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) {
      setError(err instanceof Error ? err.message : 'Failed to update status');
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Board</h1>
        <p className="text-sm text-muted-foreground">Kanban view of all items</p>
      </div>

      {error && (
        <div className="rounded-md bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {error}
        </div>
      )}

      <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>
                <span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground">
                  {colItems.length}
                </span>
              </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">
                      <span
                        className={`h-2 w-2 rounded-full ${TYPE_DOT[item.type] || 'bg-gray-400'}`}
                      />
                      <span className="text-xs text-muted-foreground">{item.type}</span>
                      <span
                        className={`ml-auto text-xs font-medium ${PRIORITY_LABEL[item.priority] || ''}`}
                      >
                        {item.priority}
                      </span>
                    </div>

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

                    <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 gap-1">
                      {COLUMNS.filter(c => c.key !== item.status).map(c => (
                        <button
                          key={c.key}
                          onClick={() => handleStatusChange(item.id, c.key)}
                          className="rounded px-1.5 py-0.5 text-[10px] text-muted-foreground hover:bg-accent hover:text-accent-foreground"
                          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>
  );
}
