import { useState } from 'react'
import DropZone from '../components/DropZone'
import { uploadDocument } from '../api/client'

interface Props {
  onTaskCreated: (taskId: string) => void
}

export default function Home({ onTaskCreated }: Props) {
  const [file, setFile] = useState<File | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSubmit = async () => {
    if (!file) return
    setLoading(true)
    setError(null)
    try {
      const res = await uploadDocument(file)
      onTaskCreated(res.task_id)
    } catch (e: unknown) {
      const msg = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail ?? 'Ошибка загрузки'
      setError(msg)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center p-6">
      <div className="bg-white rounded-2xl shadow-md p-8 w-full max-w-lg flex flex-col gap-6">
        <h1 className="text-2xl font-bold text-gray-800 text-center">Антиплагиат</h1>
        <p className="text-sm text-gray-500 text-center">
          Загрузите документ для проверки на заимствования
        </p>

        <DropZone onFile={setFile} disabled={loading} />

        {error && (
          <p className="text-red-500 text-sm text-center">{error}</p>
        )}

        <button
          onClick={handleSubmit}
          disabled={!file || loading}
          className="w-full py-3 rounded-xl bg-blue-600 text-white font-semibold hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
        >
          {loading ? 'Загрузка…' : 'Проверить'}
        </button>
      </div>
    </div>
  )
}
