'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  DndContext,
  closestCenter,
  type DragEndEvent,
  PointerSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { GripVertical, Plus, Loader2, Trash2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { apiFetch } from '@/lib/api/client';

interface WaitingListEntry {
  id: string;
  clientId: string;
  position: number;
  priority: string;
  notifyPref: string;
  notes: string | null;
  createdAt: string;
}

interface WaitingListManagerProps {
  berthId: string;
}

function SortableEntry({
  entry,
  onRemove,
}: {
  entry: WaitingListEntry;
  onRemove: (id: string) => void;
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: entry.id,
  });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className="flex items-center gap-3 border rounded-md p-3 bg-card"
    >
      <button
        {...attributes}
        {...listeners}
        className="cursor-grab active:cursor-grabbing text-muted-foreground"
      >
        <GripVertical className="h-4 w-4" aria-hidden />
      </button>

      <span className="text-sm font-mono w-6 text-center text-muted-foreground">
        {entry.position}
      </span>

      <div className="flex-1 min-w-0">
        <p className="text-sm truncate">{entry.clientId}</p>
        {entry.notes && <p className="text-xs text-muted-foreground truncate">{entry.notes}</p>}
      </div>

      <Badge variant={entry.priority === 'high' ? 'destructive' : 'secondary'}>
        {entry.priority}
      </Badge>

      <button
        onClick={() => onRemove(entry.id)}
        className="text-muted-foreground hover:text-destructive transition-colors"
      >
        <Trash2 className="h-4 w-4" aria-hidden />
      </button>
    </div>
  );
}

export function WaitingListManager({ berthId }: WaitingListManagerProps) {
  const queryClient = useQueryClient();
  const sensors = useSensors(useSensor(PointerSensor));

  const [showAddForm, setShowAddForm] = useState(false);
  const [newClientId, setNewClientId] = useState('');
  const [newPriority, setNewPriority] = useState<'normal' | 'high'>('normal');
  const [newNotes, setNewNotes] = useState('');

  const { data, isLoading } = useQuery<{ data: WaitingListEntry[] }>({
    queryKey: ['berth-waiting-list', berthId],
    queryFn: () => apiFetch(`/api/v1/berths/${berthId}/waiting-list`),
  });

  const reorderMutation = useMutation({
    mutationFn: (body: { entryId: string; newPosition: number }) =>
      apiFetch(`/api/v1/berths/${berthId}/waiting-list`, {
        method: 'PATCH',
        body,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['berth-waiting-list', berthId] });
    },
  });

  const addMutation = useMutation({
    mutationFn: (entries: WaitingListEntry[]) =>
      apiFetch(`/api/v1/berths/${berthId}/waiting-list`, {
        method: 'PUT',
        body: { entries },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['berth-waiting-list', berthId] });
      setShowAddForm(false);
      setNewClientId('');
      setNewNotes('');
    },
  });

  const entries = data?.data ?? [];

  function handleDragEnd(event: DragEndEvent) {
    const { active, over } = event;
    if (!over || active.id === over.id) return;

    const overId = over.id as string;
    const overEntry = entries.find((e) => e.id === overId);
    if (!overEntry) return;

    reorderMutation.mutate({
      entryId: active.id as string,
      newPosition: overEntry.position,
    });
  }

  function handleAdd() {
    if (!newClientId.trim()) return;
    const newEntry = {
      clientId: newClientId.trim(),
      position: entries.length + 1,
      priority: newPriority,
      notifyPref: 'email' as const,
      notes: newNotes || undefined,
    };
    addMutation.mutate([
      ...entries.map((e) => ({
        ...e,
        notifyPref: e.notifyPref as 'email' | 'in_app' | 'both',
        priority: e.priority as 'normal' | 'high',
      })),
      newEntry as WaitingListEntry,
    ]);
  }

  function handleRemove(entryId: string) {
    const remaining = entries
      .filter((e) => e.id !== entryId)
      .map((e, i) => ({
        ...e,
        position: i + 1,
        notifyPref: e.notifyPref as 'email' | 'in_app' | 'both',
        priority: e.priority as 'normal' | 'high',
      }));
    addMutation.mutate(remaining);
  }

  if (isLoading) {
    return <div className="h-24 bg-muted animate-pulse rounded" />;
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <span className="text-sm font-medium">Waiting List ({entries.length})</span>
        <Button size="sm" variant="outline" onClick={() => setShowAddForm((v) => !v)}>
          <Plus className="mr-1.5 h-4 w-4" aria-hidden />
          Add
        </Button>
      </div>

      {showAddForm && (
        <div className="border rounded-md p-3 space-y-3 bg-muted/30">
          <Input
            placeholder="Client ID"
            value={newClientId}
            onChange={(e) => setNewClientId(e.target.value)}
          />
          <Select value={newPriority} onValueChange={(v) => setNewPriority(v as 'normal' | 'high')}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="normal">Normal priority</SelectItem>
              <SelectItem value="high">High priority</SelectItem>
            </SelectContent>
          </Select>
          <Input
            placeholder="Notes (optional)"
            value={newNotes}
            onChange={(e) => setNewNotes(e.target.value)}
          />
          <div className="flex gap-2">
            <Button size="sm" onClick={handleAdd} disabled={addMutation.isPending}>
              {addMutation.isPending && (
                <Loader2 className="mr-1.5 h-4 w-4 animate-spin" aria-hidden />
              )}
              Add to List
            </Button>
            <Button size="sm" variant="ghost" onClick={() => setShowAddForm(false)}>
              Cancel
            </Button>
          </div>
        </div>
      )}

      {entries.length === 0 ? (
        <p className="text-sm text-muted-foreground text-center py-6">
          No entries on waiting list.
        </p>
      ) : (
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
          <SortableContext items={entries.map((e) => e.id)} strategy={verticalListSortingStrategy}>
            <div className="space-y-2">
              {entries.map((entry) => (
                <SortableEntry key={entry.id} entry={entry} onRemove={handleRemove} />
              ))}
            </div>
          </SortableContext>
        </DndContext>
      )}
    </div>
  );
}
