import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { Plus, RefreshCw, Play, Power, AlertTriangle, CheckCircle2, Clock, Pause } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Button, Badge, Card, Skeleton, EmptyState } from '../../components/ui/primitives';
import { Table, THead, TBody, TR, TH, TD } from '../../components/ui/table';
import type { Feed } from './types';

function formatDate(iso: string | null) {
  if (!iso) return '—';
  const d = new Date(iso);
  const now = new Date();
  const diff = (now.getTime() - d.getTime()) / 1000;
  if (diff < 60) return 'net';
  if (diff < 3600) return `${Math.floor(diff / 60)}m`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}u`;
  return `${Math.floor(diff / 86400)}d`;
}

function statusBadge(feed: Feed) {
  if (!feed.is_active) return <Badge variant="muted">Uit</Badge>;
  if (feed.consecutive_failures >= 3) return <Badge variant="danger">Fout</Badge>;
  if (feed.last_error && feed.consecutive_failures > 0) return <Badge variant="warn">Waarschuwing</Badge>;
  if (!feed.last_synced_at) return <Badge variant="info">Nieuw</Badge>;
  return <Badge variant="success">Actief</Badge>;
}

function HealthDot({ feed }: { feed: Feed }) {
  let color = 'bg-[#666]';
  let Icon = Pause;
  if (feed.is_active) {
    if (feed.consecutive_failures >= 3) {
      color = 'bg-[#FF3B3B]';
      Icon = AlertTriangle;
    } else if (feed.consecutive_failures > 0) {
      color = 'bg-[#FFA500]';
      Icon = AlertTriangle;
    } else if (feed.last_success_at) {
      color = 'bg-[#00FF6A]';
      Icon = CheckCircle2;
    } else {
      color = 'bg-[#3B82F6]';
      Icon = Clock;
    }
  }
  return (
    <div className="flex items-center gap-2">
      <div className={`h-2 w-2 rounded-full ${color}`} />
      <Icon className="h-3.5 w-3.5 text-[#666]" />
    </div>
  );
}

export function FeedsList() {
  const qc = useQueryClient();
  const navigate = useNavigate();
  const [syncingAll, setSyncingAll] = useState(false);

  const { data, isLoading } = useQuery({
    queryKey: ['feeds'],
    queryFn: () => api.get<{ feeds: Feed[] }>('/feeds'),
    refetchInterval: 10000,
  });

  const syncMut = useMutation({
    mutationFn: (id: number) => api.post<{ jobId: number }>(`/feeds/${id}/sync`),
    onSuccess: (res) => {
      toast.success(`Sync gestart (job #${res.jobId})`);
      qc.invalidateQueries({ queryKey: ['feeds'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const toggleMut = useMutation({
    mutationFn: ({ id, is_active }: { id: number; is_active: boolean }) =>
      api.put<{ feed: Feed }>(`/feeds/${id}`, { is_active }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['feeds'] });
      toast.success('Feed bijgewerkt');
    },
    onError: (e: Error) => toast.error(e.message),
  });

  async function syncAll() {
    setSyncingAll(true);
    try {
      const res = await api.post<{ enqueued: number }>('/feeds/sync-all');
      toast.success(`${res.enqueued} feeds in de wachtrij`);
      qc.invalidateQueries({ queryKey: ['feeds'] });
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Sync all mislukt');
    } finally {
      setSyncingAll(false);
    }
  }

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

  return (
    <AppShell>
      <PageHeader
        title="Feeds"
        description="Alle affiliate-feeds met live sync-status."
        actions={
          <>
            <Button variant="secondary" size="sm" onClick={syncAll} disabled={syncingAll}>
              <RefreshCw className={`h-4 w-4 ${syncingAll ? 'animate-spin' : ''}`} />
              Sync alles
            </Button>
            <Button size="sm" onClick={() => navigate('/cms/feeds/new')}>
              <Plus className="h-4 w-4" />
              Nieuwe feed
            </Button>
          </>
        }
      />
      <PageBody>
        <Card>
          {isLoading ? (
            <div className="p-6 space-y-3">
              {[0, 1, 2, 3].map((i) => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : feeds.length === 0 ? (
            <EmptyState
              title="Nog geen feeds"
              description="Voeg een affiliate-feed toe om producten binnen te halen."
              action={
                <Button onClick={() => navigate('/cms/feeds/new')}>
                  <Plus className="h-4 w-4" />
                  Nieuwe feed
                </Button>
              }
            />
          ) : (
            <Table>
              <THead>
                <TR className="hover:bg-transparent">
                  <TH className="w-[80px]">Status</TH>
                  <TH>Naam</TH>
                  <TH>Provider</TH>
                  <TH className="text-right">Producten</TH>
                  <TH>Laatste sync</TH>
                  <TH>Status</TH>
                  <TH className="text-right w-[180px]">Acties</TH>
                </TR>
              </THead>
              <TBody>
                {feeds.map((feed) => (
                  <TR key={feed.id} className="cursor-pointer">
                    <TD>
                      <HealthDot feed={feed} />
                    </TD>
                    <TD>
                      <Link to={`/cms/feeds/${feed.id}`} className="font-medium text-[#F5F5F5] hover:text-[#00FF6A]">
                        {feed.name}
                      </Link>
                      {feed.last_error && feed.consecutive_failures > 0 && (
                        <p className="text-[11px] text-[#FF3B3B] mt-0.5 truncate max-w-[340px]">
                          {feed.last_error}
                        </p>
                      )}
                    </TD>
                    <TD className="text-xs text-[#999]">
                      {feed.provider_name ?? feed.provider_slug ?? '—'}
                    </TD>
                    <TD className="text-right tabular-nums text-[#F5F5F5]">
                      {feed.total_products?.toLocaleString('nl-NL') ?? '0'}
                    </TD>
                    <TD className="text-xs text-[#999]">{formatDate(feed.last_synced_at)}</TD>
                    <TD>{statusBadge(feed)}</TD>
                    <TD className="text-right">
                      <div className="flex justify-end gap-1">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={(e) => {
                            e.stopPropagation();
                            syncMut.mutate(feed.id);
                          }}
                          disabled={syncMut.isPending}
                          title="Sync nu"
                        >
                          <Play className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={(e) => {
                            e.stopPropagation();
                            toggleMut.mutate({ id: feed.id, is_active: !feed.is_active });
                          }}
                          title={feed.is_active ? 'Uitschakelen' : 'Inschakelen'}
                        >
                          <Power className={`h-4 w-4 ${feed.is_active ? 'text-[#00FF6A]' : 'text-[#666]'}`} />
                        </Button>
                      </div>
                    </TD>
                  </TR>
                ))}
              </TBody>
            </Table>
          )}
        </Card>
      </PageBody>
    </AppShell>
  );
}
