import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { RefreshCw, XCircle, Play, AlertCircle, Clock, CheckCircle2 } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Badge, Button, Card, Select } from '../../components/ui/primitives';
import { Table, THead, TBody, TR, TH, TD } from '../../components/ui/table';

interface Job {
  id: number;
  type: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
  priority: number;
  attempts: number;
  max_attempts: number;
  progress: number;
  actor_email: string | null;
  error: string | null;
  created_at: string;
  started_at: string | null;
  finished_at: string | null;
}

interface Stats {
  pending: number;
  running: number;
  completed: number;
  failed: number;
  cancelled: number;
  total: number;
}

const STATUS_VARIANTS: Record<Job['status'], 'muted' | 'info' | 'success' | 'danger' | 'warn'> = {
  pending: 'muted',
  running: 'info',
  completed: 'success',
  failed: 'danger',
  cancelled: 'warn',
};

export function JobsList() {
  const qc = useQueryClient();
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [typeFilter, setTypeFilter] = useState<string>('');

  const { data: jobsData } = useQuery({
    queryKey: ['jobs', statusFilter, typeFilter],
    queryFn: () =>
      api.get<{ jobs: Job[] }>('/jobs', {
        status: statusFilter || undefined,
        type: typeFilter || undefined,
        limit: 200,
      }),
    refetchInterval: 3000,
  });

  const { data: stats } = useQuery({
    queryKey: ['jobs-stats'],
    queryFn: () => api.get<Stats>('/jobs/stats'),
    refetchInterval: 3000,
  });

  const retryMut = useMutation({
    mutationFn: (id: number) => api.post(`/jobs/${id}/retry`),
    onSuccess: () => {
      toast.success('Job opnieuw in wachtrij');
      qc.invalidateQueries({ queryKey: ['jobs'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const cancelMut = useMutation({
    mutationFn: (id: number) => api.post(`/jobs/${id}/cancel`),
    onSuccess: () => {
      toast.success('Job geannuleerd');
      qc.invalidateQueries({ queryKey: ['jobs'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const jobs = jobsData?.jobs ?? [];

  return (
    <AppShell>
      <PageHeader
        title="Job queue"
        description="Background jobs: feed sync, AI descriptions, email/push sends."
      />
      <PageBody>
        <div className="grid grid-cols-5 gap-3 mb-4">
          <StatCard label="Pending" value={stats?.pending ?? 0} icon={<Clock className="h-4 w-4" />} />
          <StatCard label="Running" value={stats?.running ?? 0} icon={<Play className="h-4 w-4 text-[#3B82F6]" />} />
          <StatCard label="Completed" value={stats?.completed ?? 0} icon={<CheckCircle2 className="h-4 w-4 text-[#00FF6A]" />} />
          <StatCard label="Failed" value={stats?.failed ?? 0} icon={<AlertCircle className="h-4 w-4 text-[#FF3B3B]" />} />
          <StatCard label="Cancelled" value={stats?.cancelled ?? 0} icon={<XCircle className="h-4 w-4 text-[#FFA500]" />} />
        </div>

        <Card>
          <div className="px-5 py-3 border-b border-[#333] flex items-center gap-3">
            <Select className="w-40" value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
              <option value="">Alle status</option>
              <option value="pending">Pending</option>
              <option value="running">Running</option>
              <option value="completed">Completed</option>
              <option value="failed">Failed</option>
              <option value="cancelled">Cancelled</option>
            </Select>
            <Select className="w-52" value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)}>
              <option value="">Alle types</option>
              <option value="feed.sync">feed.sync</option>
              <option value="product.regen-description">product.regen-description</option>
              <option value="product.bulk-update">product.bulk-update</option>
              <option value="email.send-test">email.send-test</option>
              <option value="email.send-campaign">email.send-campaign</option>
              <option value="push.send">push.send</option>
            </Select>
            <div className="ml-auto text-xs text-[#666]">Auto-refresh 3s</div>
          </div>
          <Table>
            <THead>
              <TR className="hover:bg-transparent">
                <TH className="w-16">#</TH>
                <TH>Type</TH>
                <TH>Status</TH>
                <TH>Progress</TH>
                <TH>Attempts</TH>
                <TH>Duur</TH>
                <TH>Aangemaakt</TH>
                <TH></TH>
              </TR>
            </THead>
            <TBody>
              {jobs.map((j) => {
                const duration =
                  j.started_at && j.finished_at
                    ? Math.round((new Date(j.finished_at).getTime() - new Date(j.started_at).getTime()) / 1000)
                    : null;
                return (
                  <TR key={j.id}>
                    <TD className="font-mono text-xs text-[#666]">{j.id}</TD>
                    <TD className="font-mono text-xs">{j.type}</TD>
                    <TD>
                      <Badge variant={STATUS_VARIANTS[j.status]}>{j.status}</Badge>
                    </TD>
                    <TD className="w-40">
                      {j.status === 'running' ? (
                        <div className="flex items-center gap-2">
                          <div className="flex-1 h-1.5 bg-[#1A1A1A] rounded-full overflow-hidden">
                            <div className="h-full bg-[#00FF6A]" style={{ width: `${j.progress}%` }} />
                          </div>
                          <span className="text-xs text-[#999] w-8">{j.progress}%</span>
                        </div>
                      ) : (
                        <span className="text-xs text-[#666]">—</span>
                      )}
                    </TD>
                    <TD className="text-xs text-[#999]">
                      {j.attempts}/{j.max_attempts}
                    </TD>
                    <TD className="text-xs text-[#999]">{duration !== null ? `${duration}s` : '—'}</TD>
                    <TD className="text-xs text-[#999]">
                      {new Date(j.created_at).toLocaleString('nl-NL')}
                    </TD>
                    <TD className="text-right">
                      {(j.status === 'failed' || j.status === 'cancelled') && (
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={() => retryMut.mutate(j.id)}
                          title="Retry"
                        >
                          <RefreshCw className="h-4 w-4" />
                        </Button>
                      )}
                      {(j.status === 'pending' || j.status === 'running') && (
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={() => cancelMut.mutate(j.id)}
                          title="Cancel"
                        >
                          <XCircle className="h-4 w-4 text-[#FF3B3B]" />
                        </Button>
                      )}
                    </TD>
                  </TR>
                );
              })}
            </TBody>
          </Table>
          {jobs.length === 0 && (
            <div className="p-10 text-center text-sm text-[#666]">Geen jobs voor deze filters.</div>
          )}
        </Card>

        {jobs.some((j) => j.error) && (
          <Card className="mt-4">
            <div className="px-5 py-3 border-b border-[#333]">
              <h3 className="text-sm font-semibold text-[#F5F5F5]">Recente fouten</h3>
            </div>
            <div className="divide-y divide-[#222]">
              {jobs
                .filter((j) => j.error)
                .slice(0, 10)
                .map((j) => (
                  <div key={j.id} className="px-5 py-3">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="font-mono text-xs text-[#666]">#{j.id}</span>
                      <span className="font-mono text-xs">{j.type}</span>
                    </div>
                    <p className="text-xs text-[#FF3B3B] font-mono whitespace-pre-wrap">{j.error}</p>
                  </div>
                ))}
            </div>
          </Card>
        )}
      </PageBody>
    </AppShell>
  );
}

function StatCard({ label, value, icon }: { label: string; value: number; icon: React.ReactNode }) {
  return (
    <Card className="px-4 py-3">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-xs text-[#999]">{label}</p>
          <p className="text-2xl font-semibold text-[#F5F5F5] mt-0.5">{value}</p>
        </div>
        <div className="text-[#666]">{icon}</div>
      </div>
    </Card>
  );
}
