'use client';

import { useState } from 'react';
import { uploadPDF } from '@/lib/api';
import { X, UploadCloud, Loader2 } from 'lucide-react';

interface UploadModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function UploadModal({ isOpen, onClose }: UploadModalProps) {
  const [file, setFile] = useState<File | null>(null);
  const [newspaper, setNewspaper] = useState('Andhra Jyothi');
  const [edition, setEdition] = useState('Main');
  const [date, setDate] = useState(new Date().toISOString().split('T')[0]);
  const [loading, setLoading] = useState(false);
  const [taskId, setTaskId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  if (!isOpen) return null;

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setFile(e.target.files[0]);
    }
  };

  const handleUpload = async () => {
    if (!file) {
      setError('Please select a PDF file.');
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const res = await uploadPDF(file, newspaper, edition, date);
      setTaskId(res.task_id);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
      <div className="w-full max-w-md rounded-2xl border border-zinc-800 bg-zinc-950 p-6 shadow-2xl">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-xl font-semibold text-zinc-100">Upload Newspaper</h2>
          <button onClick={onClose} className="rounded-full p-2 text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100">
            <X size={20} />
          </button>
        </div>

        {taskId ? (
          <div className="text-center py-8">
            <div className="mb-4 inline-flex h-12 w-12 items-center justify-center rounded-full bg-emerald-500/20 text-emerald-400">
              <UploadCloud size={24} />
            </div>
            <h3 className="mb-2 text-lg font-medium text-zinc-100">Upload Successful</h3>
            <p className="text-sm text-zinc-400">
              Task queued for processing. It may take a few minutes for the pipeline to extract all data.
            </p>
            <p className="mt-4 text-xs font-mono text-zinc-500">Task ID: {taskId}</p>
            <button
              onClick={() => {
                setTaskId(null);
                setFile(null);
                onClose();
              }}
              className="mt-6 w-full rounded-lg bg-zinc-800 py-2 text-sm font-medium text-zinc-200 hover:bg-zinc-700"
            >
              Close
            </button>
          </div>
        ) : (
          <div className="space-y-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-zinc-400">Newspaper PDF</label>
              <div className="relative flex w-full cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed border-zinc-800 bg-zinc-900/50 py-8 hover:border-zinc-700 hover:bg-zinc-900">
                <input
                  type="file"
                  accept="application/pdf"
                  className="absolute inset-0 z-10 h-full w-full cursor-pointer opacity-0"
                  onChange={handleFileChange}
                />
                <UploadCloud className="mb-2 text-zinc-500" size={32} />
                <span className="text-sm font-medium text-zinc-300">
                  {file ? file.name : 'Click or drag PDF to upload'}
                </span>
                <span className="mt-1 text-xs text-zinc-500">Max size 50MB</span>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="mb-1 block text-sm font-medium text-zinc-400">Newspaper</label>
                <input
                  type="text"
                  value={newspaper}
                  onChange={e => setNewspaper(e.target.value)}
                  className="w-full rounded-lg border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-600 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-zinc-400">Edition</label>
                <input
                  type="text"
                  value={edition}
                  onChange={e => setEdition(e.target.value)}
                  className="w-full rounded-lg border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-600 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                />
              </div>
            </div>

            <div>
              <label className="mb-1 block text-sm font-medium text-zinc-400">Date</label>
              <input
                type="date"
                value={date}
                onChange={e => setDate(e.target.value)}
                className="w-full rounded-lg border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
              />
            </div>

            {error && (
              <div className="rounded-lg bg-red-500/10 p-3 text-sm text-red-400 border border-red-500/20">
                {error}
              </div>
            )}

            <button
              onClick={handleUpload}
              disabled={loading || !file}
              className="mt-2 flex w-full items-center justify-center rounded-lg bg-indigo-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {loading ? (
                <>
                  <Loader2 className="mr-2 animate-spin" size={16} />
                  Uploading...
                </>
              ) : (
                'Start Ingestion Pipeline'
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
