import { useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { useFailures, useBulkRetry, useUploadFinalVtt } from '../../hooks/useJob';
import { StatusBadge } from '../../components/StatusBadge';
import { useToastContext } from '../../contexts/ToastContext';
import { useAuthStore } from '../../lib/auth';

const STEP_LABELS: Record<string, string> = {
  ingestion: 'Ingestion',
  ai_processing: 'AI Processing',
  translation: 'Translation',
  tts: 'TTS',
  render: 'Render',
};

export function FailuresList() {
  const [stepFilter, setStepFilter] = useState('');
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [strategy, setStrategy] = useState<'auto' | 'from_scratch'>('auto');
  const [uploadTarget, setUploadTarget] = useState<{ jobId: string; title: string } | null>(null);
  const [uploadLanguage, setUploadLanguage] = useState('en');
  const [uploadType, setUploadType] = useState<'captions' | 'ad'>('captions');
  const uploadFileRef = useRef<HTMLInputElement>(null);
  const toast = useToastContext();
  const { user } = useAuthStore();
  const canUploadVtt = user?.role === 'production' || user?.role === 'admin';

  const { data: jobs = [], isLoading, error, refetch } = useFailures(
    stepFilter ? { step: stepFilter } : undefined
  );
  const bulkRetryMutation = useBulkRetry();
  const uploadVttMutation = useUploadFinalVtt();

  const toggle = (id: string) => {
    const next = new Set(selected);
    if (next.has(id)) { next.delete(id); } else { next.add(id); }
    setSelected(next);
  };
  const selectAll = () => setSelected(new Set(jobs.map(j => j.id)));
  const clearSelection = () => setSelected(new Set());

  const handleBulkRetry = async () => {
    if (selected.size === 0) return;
    const ids = [...selected];
    try {
      const result = await bulkRetryMutation.mutateAsync({ job_ids: ids, strategy });
      toast.toastOnly.success(
        `Retried ${result.retried.length} job(s). Skipped: ${result.skipped.length}. Errors: ${result.errors.length}.`
      );
      clearSelection();
      refetch();
    } catch {
      toast.toastOnly.error('Bulk retry failed');
    }
  };

  const handleUploadVtt = async () => {
    if (!uploadTarget || !uploadFileRef.current?.files?.[0]) return;
    const file = uploadFileRef.current.files[0];
    try {
      await uploadVttMutation.mutateAsync({
        jobId: uploadTarget.jobId,
        language: uploadLanguage,
        vttFile: file,
        vttType: uploadType,
      });
      toast.toastOnly.success(`VTT uploaded — job advanced to Pending QC`);
      setUploadTarget(null);
    } catch {
      toast.toastOnly.error('VTT upload failed');
    }
  };

  // Group by failure type for accordion
  const byType = jobs.reduce<Record<string, typeof jobs>>((acc, job) => {
    const key = job.failure?.type || job.status;
    acc[key] = acc[key] ?? [];
    acc[key].push(job);
    return acc;
  }, {});

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          {[...Array(5)].map((_, i) => <div key={i} className="h-14 bg-gray-200 rounded"></div>)}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="bg-red-50 border border-red-200 rounded-md p-4">
          <p className="text-red-600">Failed to load failures dashboard.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Failures Dashboard</h1>
        <div className="flex items-center gap-3">
          <select
            value={stepFilter}
            onChange={e => setStepFilter(e.target.value)}
            className="border border-gray-300 rounded px-3 py-1.5 text-sm"
          >
            <option value="">All steps</option>
            {Object.entries(STEP_LABELS).map(([k, v]) => (
              <option key={k} value={k}>{v}</option>
            ))}
          </select>
        </div>
      </div>

      {jobs.length === 0 ? (
        <div className="bg-green-50 border border-green-200 rounded-md p-6 text-center">
          <p className="text-green-700 font-medium">No failures — all clear!</p>
        </div>
      ) : (
        <>
          {/* Bulk actions bar */}
          {selected.size > 0 && (
            <div className="flex items-center gap-3 bg-orange-50 border border-orange-200 rounded-lg px-4 py-3 mb-4">
              <span className="text-sm font-medium text-orange-800">{selected.size} selected</span>
              <select
                value={strategy}
                onChange={e => setStrategy(e.target.value as 'auto' | 'from_scratch')}
                className="border border-orange-300 rounded px-2 py-1 text-sm"
              >
                <option value="auto">Auto (from failure step)</option>
                <option value="from_scratch">From scratch (re-ingest)</option>
              </select>
              <button
                onClick={handleBulkRetry}
                disabled={bulkRetryMutation.isPending}
                className="px-4 py-1.5 bg-orange-600 text-white text-sm rounded hover:bg-orange-700 disabled:opacity-50"
              >
                {bulkRetryMutation.isPending ? 'Retrying...' : 'Retry selected'}
              </button>
              <button onClick={clearSelection} className="text-sm text-gray-500 hover:text-gray-700">
                Clear
              </button>
            </div>
          )}

          <div className="mb-3 flex gap-3 text-sm text-gray-500">
            <button onClick={selectAll} className="hover:text-gray-800">Select all</button>
            <span>|</span>
            <span>{jobs.length} failure{jobs.length !== 1 ? 's' : ''} total</span>
          </div>

          {/* Grouped by error type */}
          <div className="space-y-4">
            {Object.entries(byType).map(([type, group]) => (
              <details key={type} className="bg-white border border-gray-200 rounded-lg" open>
                <summary className="flex items-center justify-between px-4 py-3 cursor-pointer select-none">
                  <span className="font-medium text-gray-800 text-sm">{type}</span>
                  <span className="text-xs text-gray-500 bg-gray-100 rounded-full px-2 py-0.5">{group.length}</span>
                </summary>
                <div className="border-t border-gray-100">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50 text-xs text-gray-500 uppercase">
                      <tr>
                        <th className="w-8 px-3 py-2"></th>
                        <th className="px-3 py-2 text-left">Title</th>
                        <th className="px-3 py-2 text-left">Status</th>
                        <th className="px-3 py-2 text-left">Step</th>
                        <th className="px-3 py-2 text-left max-w-xs">Message</th>
                        <th className="px-3 py-2 text-left">Retries</th>
                        <th className="px-3 py-2 text-left">Updated</th>
                        <th className="px-3 py-2"></th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {group.map(job => (
                        <tr key={job.id} className={`hover:bg-gray-50 ${selected.has(job.id) ? 'bg-orange-50' : ''}`}>
                          <td className="px-3 py-2">
                            <input
                              type="checkbox"
                              checked={selected.has(job.id)}
                              onChange={() => toggle(job.id)}
                              className="rounded border-gray-300"
                            />
                          </td>
                          <td className="px-3 py-2 font-medium text-gray-900 max-w-xs truncate">
                            {job.title}
                          </td>
                          <td className="px-3 py-2">
                            <StatusBadge status={job.status} />
                          </td>
                          <td className="px-3 py-2 text-gray-600">
                            {job.failure?.step ? STEP_LABELS[job.failure.step] ?? job.failure.step : '—'}
                          </td>
                          <td className="px-3 py-2 text-gray-500 max-w-xs">
                            <span className="line-clamp-2 text-xs">{job.failure?.message || '—'}</span>
                          </td>
                          <td className={`px-3 py-2 font-medium ${(job.failure?.retry_count ?? 0) > 3 ? 'text-red-600' : 'text-gray-600'}`}>
                            {job.failure?.retry_count ?? 0}
                          </td>
                          <td className="px-3 py-2 text-gray-400 whitespace-nowrap text-xs">
                            {new Date(job.updated_at).toLocaleDateString()}
                          </td>
                          <td className="px-3 py-2 flex items-center gap-2">
                            <Link
                              to={`/jobs/${job.id}`}
                              className="text-indigo-600 hover:text-indigo-800 text-xs"
                            >
                              View
                            </Link>
                            {canUploadVtt && (
                              <button
                                onClick={() => setUploadTarget({ jobId: job.id, title: job.title })}
                                className="text-xs text-emerald-600 hover:text-emerald-800"
                                title="Upload final VTT to bypass AI"
                              >
                                Upload VTT
                              </button>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </details>
            ))}
          </div>
        </>
      )}

      {/* Upload final VTT modal */}
      {uploadTarget && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="bg-white rounded-xl shadow-xl p-6 w-full max-w-md">
            <h2 className="text-lg font-semibold text-gray-900 mb-1">Upload Final VTT</h2>
            <p className="text-sm text-gray-500 mb-4">
              Override AI output for <span className="font-medium">{uploadTarget.title}</span> and advance to Pending QC.
            </p>
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-medium text-gray-700 mb-1">Language (BCP-47)</label>
                <input
                  type="text"
                  value={uploadLanguage}
                  onChange={e => setUploadLanguage(e.target.value)}
                  placeholder="en"
                  className="w-full border border-gray-300 rounded px-3 py-1.5 text-sm"
                />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-700 mb-1">VTT type</label>
                <select
                  value={uploadType}
                  onChange={e => setUploadType(e.target.value as 'captions' | 'ad')}
                  className="w-full border border-gray-300 rounded px-3 py-1.5 text-sm"
                >
                  <option value="captions">Closed Captions</option>
                  <option value="ad">Audio Description</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-700 mb-1">VTT file</label>
                <input ref={uploadFileRef} type="file" accept=".vtt" className="text-sm" />
              </div>
            </div>
            <div className="flex justify-end gap-3 mt-5">
              <button
                onClick={() => setUploadTarget(null)}
                className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800"
              >
                Cancel
              </button>
              <button
                onClick={handleUploadVtt}
                disabled={uploadVttMutation.isPending}
                className="px-4 py-2 bg-emerald-600 text-white text-sm rounded hover:bg-emerald-700 disabled:opacity-50"
              >
                {uploadVttMutation.isPending ? 'Uploading...' : 'Upload & Advance'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
