import { type FormEvent, useState } from 'react'
import type { BulkImportResult } from '../../types'

interface BulkImportModalProps {
  title: string
  example?: string
  onSubmit: (items: unknown[]) => Promise<BulkImportResult>
  onClose: () => void
  /** Label for the "created" count in the result summary */
  createdLabel?: string
  /** Label for the "updated" count in the result summary */
  updatedLabel?: string
}

export function BulkImportModal({ title, example, onSubmit, onClose, createdLabel = 'Created', updatedLabel = 'Updated' }: BulkImportModalProps) {
  const [json, setJson] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [result, setResult] = useState<BulkImportResult | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(null)
    setResult(null)

    let items: unknown[]
    try {
      items = JSON.parse(json)
      if (!Array.isArray(items)) throw new Error('Must be an array')
    } catch {
      setError('Invalid JSON. Must be an array of objects.')
      return
    }

    setIsSubmitting(true)
    try {
      const res = await onSubmit(items)
      setResult(res)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Import failed')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="fixed inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold">{title}</h2>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="px-6 py-4 space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">
                JSON Data
              </label>
              <textarea
                rows={12}
                value={json}
                onChange={(e) => setJson(e.target.value)}
                placeholder={example}
                className="w-full px-3 py-2 border rounded-md font-mono text-sm dark:bg-gray-700 dark:border-gray-600"
              />
            </div>

            {error && (
              <div className="p-3 bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300 rounded-md text-sm">
                {error}
              </div>
            )}

            {result && (
              <div className="p-3 bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-md text-sm">
                <p>{createdLabel}: {result.created}, {updatedLabel}: {result.updated}</p>
                {result.errors.length > 0 && (
                  <ul className="mt-2 list-disc list-inside text-red-600 dark:text-red-400">
                    {result.errors.map((err, i) => (
                      <li key={i}>{err}</li>
                    ))}
                  </ul>
                )}
              </div>
            )}
          </div>
          <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium rounded-md border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              Close
            </button>
            <button
              type="submit"
              disabled={isSubmitting || !json.trim()}
              className="px-4 py-2 text-sm font-medium rounded-md bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
            >
              {isSubmitting ? 'Importing...' : 'Import'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
