import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { ShieldAlert, RotateCcw, Trash2, AlertCircle } from 'lucide-react';
import { quarantineService } from '../services/quarantineService';
import { Badge } from '../components/ethos/Badge';
import { PageContainer } from '../components/PageContainer';
import { PageHeader } from '../components/PageHeader';
import { EmptyState } from '../components/EmptyState';
import { SkeletonRows } from '../components/LoadingState';
import { toast } from '../store/useToastStore';
import type { DislikeEntry } from '../types';

function countdown(entry: DislikeEntry): string {
  const base = entry.warned_at
    ? new Date(entry.warned_at).getTime() + 24 * 3600 * 1000
    : new Date(entry.disliked_at).getTime() + entry.grace_hours * 3600 * 1000;
  const ms = base - Date.now();
  if (ms <= 0) return 'Deleting soon';
  const h = Math.floor(ms / 3600000);
  const m = Math.floor((ms % 3600000) / 60000);
  return h > 0 ? `${h}h ${m}m remaining` : `${m}m remaining`;
}

function stateLabel(state: string) {
  if (state === 'WARNED') return <Badge color="amber">Warning sent</Badge>;
  return <Badge color="neutral">Grace period</Badge>;
}

export default function Quarantine() {
  const qc = useQueryClient();
  const { data, isLoading, isError } = useQuery<DislikeEntry[]>({
    queryKey: ['dislikes'],
    queryFn: () => quarantineService.list(),
    refetchInterval: 60_000,
  });

  const restore = useMutation({
    mutationFn: (trackId: string) => quarantineService.restore(trackId),
    onSuccess: (_d, trackId) => {
      qc.invalidateQueries({ queryKey: ['dislikes'] });
      qc.invalidateQueries({ queryKey: ['tracks'] });
      toast.success('Track restored to library', { ttl: 5000 });
      void trackId;
    },
    onError: () => toast.error("Couldn't restore the track. Try again."),
  });

  const hardDelete = useMutation({
    mutationFn: (trackId: string) => quarantineService.hardDelete(trackId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['dislikes'] });
      toast.success('Track deleted permanently');
    },
    onError: () => toast.error("Couldn't delete the track. Try again."),
  });

  const entries = data ?? [];

  return (
    <PageContainer>
      <PageHeader
        title="Quarantine"
        subtitle="Disliked tracks pending deletion. Restore before the timer expires."
        meta={entries.length ? `${entries.length} held` : undefined}
      />

      {isLoading ? <SkeletonRows count={3} />
        : isError ? <EmptyState compact icon={<AlertCircle size={28} />} title="Couldn't load quarantine list" subtitle="Something went wrong. Try reloading the page." />
        : entries.length === 0 ? (
          <EmptyState
            icon={<ShieldAlert size={28} />}
            title="No tracks in quarantine"
            subtitle="Disliked tracks will appear here during the grace period before being deleted."
          />
        ) : (
          <ul className="track-list rounded-lg border border-border bg-surface0/40 px-1.5">
            {entries.map((entry) => (
              <li key={entry.track_id} className="flex h-14 items-center gap-2.5">
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <span className="truncate text-sm font-medium text-text">{entry.track_title}</span>
                    {stateLabel(entry.state)}
                  </div>
                  <div className="truncate text-xs text-secondary">{entry.track_artist}</div>
                </div>
                <span className="flex-none font-mono text-xs tabular-nums text-machine">{countdown(entry)}</span>
                <div className="flex flex-none items-center gap-1.5">
                  <button
                    onClick={() => restore.mutate(entry.track_id)}
                    disabled={restore.isPending}
                    title="Restore to library"
                    className="flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-text transition-colors hover:bg-surface1 disabled:opacity-50"
                  >
                    <RotateCcw size={14} /> Restore
                  </button>
                  <button
                    onClick={() => { if (confirm(`Permanently delete "${entry.track_title}"?`)) hardDelete.mutate(entry.track_id); }}
                    disabled={hardDelete.isPending}
                    title="Delete now"
                    className="flex items-center gap-1.5 rounded-md border border-red-500/40 px-2 py-1 text-xs text-red-400 transition-colors hover:bg-red-500/10 disabled:opacity-50"
                  >
                    <Trash2 size={14} /> Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
    </PageContainer>
  );
}
