"use client"

import { useState } from "react"
import Link from "next/link"
import { importHanzi } from "@/actions/admin"
import type { ImportResult } from "@/lib/import/types"

export default function AdminImportPage() {
  const [inputMethod, setInputMethod] = useState<"file" | "paste">("file")
  const [file, setFile] = useState<File | null>(null)
  const [pastedData, setPastedData] = useState("")
  const [format, setFormat] = useState<"json" | "csv">("json")
  const [updateExisting, setUpdateExisting] = useState(true)
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<ImportResult | null>(null)
  const [error, setError] = useState<string | null>(null)

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0]
    if (selectedFile) {
      setFile(selectedFile)
      setResult(null)
      setError(null)

      // Auto-detect format from file extension
      if (selectedFile.name.endsWith(".json")) {
        setFormat("json")
      } else if (selectedFile.name.endsWith(".csv")) {
        setFormat("csv")
      }
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    let dataToImport: string

    if (inputMethod === "file") {
      if (!file) {
        setError("Please select a file")
        return
      }
      dataToImport = await file.text()
    } else {
      if (!pastedData.trim()) {
        setError("Please paste some data")
        return
      }
      dataToImport = pastedData
    }

    setLoading(true)
    setError(null)
    setResult(null)

    try {
      const response = await importHanzi(dataToImport, format, updateExisting)

      if (response.success && response.data) {
        setResult(response.data)
        // Clear input after successful import
        if (inputMethod === "paste") {
          setPastedData("")
        } else {
          setFile(null)
        }
      } else {
        setError(response.message || "Import failed")
        if (response.data) {
          setResult(response.data)
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-4xl">
      <div className="mb-6">
        <h1 className="text-3xl font-bold mb-2">Import Hanzi Data</h1>
        <div className="flex gap-4 text-sm">
          <span className="text-blue-600 dark:text-blue-400 font-semibold">Import</span>
          <Link
            href="/admin/initialize"
            className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
          >
            Initialize
          </Link>
        </div>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <h2 className="text-xl font-semibold mb-4">Import Data</h2>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">
              Input Method
            </label>
            <div className="flex gap-4">
              <label className="flex items-center">
                <input
                  type="radio"
                  value="file"
                  checked={inputMethod === "file"}
                  onChange={(e) => setInputMethod(e.target.value as "file" | "paste")}
                  className="mr-2"
                  disabled={loading}
                />
                Upload File
              </label>
              <label className="flex items-center">
                <input
                  type="radio"
                  value="paste"
                  checked={inputMethod === "paste"}
                  onChange={(e) => setInputMethod(e.target.value as "file" | "paste")}
                  className="mr-2"
                  disabled={loading}
                />
                Paste Data
              </label>
            </div>
          </div>

          {inputMethod === "file" ? (
            <div>
              <label className="block text-sm font-medium mb-2">
                Select File
              </label>
              <input
                type="file"
                accept=".json,.csv"
                onChange={handleFileChange}
                className="block w-full text-sm text-gray-900 border border-gray-300 rounded-lg cursor-pointer bg-gray-50 dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400"
                disabled={loading}
              />
            </div>
          ) : (
            <div>
              <label className="block text-sm font-medium mb-2">
                Paste Data
              </label>
              <textarea
                value={pastedData}
                onChange={(e) => setPastedData(e.target.value)}
                placeholder={`Paste your ${format.toUpperCase()} data here...`}
                className="block w-full h-64 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 font-mono"
                disabled={loading}
              />
            </div>
          )}

          <div>
            <label className="block text-sm font-medium mb-2">Format</label>
            <div className="flex gap-4">
              <label className="flex items-center">
                <input
                  type="radio"
                  value="json"
                  checked={format === "json"}
                  onChange={(e) => setFormat(e.target.value as "json" | "csv")}
                  className="mr-2"
                  disabled={loading}
                />
                JSON (HSK Vocabulary)
              </label>
              <label className="flex items-center">
                <input
                  type="radio"
                  value="csv"
                  checked={format === "csv"}
                  onChange={(e) => setFormat(e.target.value as "json" | "csv")}
                  className="mr-2"
                  disabled={loading}
                />
                CSV
              </label>
            </div>
          </div>

          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={updateExisting}
                onChange={(e) => setUpdateExisting(e.target.checked)}
                className="mr-2"
                disabled={loading}
              />
              <span className="text-sm font-medium">
                Update existing entries
              </span>
            </label>
            <p className="text-xs text-gray-600 dark:text-gray-400 mt-1 ml-6">
              {updateExisting
                ? "Existing hanzi will be updated with new data"
                : "Existing hanzi will be skipped (only new ones will be added)"}
            </p>
          </div>

          <button
            type="submit"
            disabled={loading || (inputMethod === "file" && !file) || (inputMethod === "paste" && !pastedData.trim())}
            className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
          >
            {loading ? "Importing..." : "Import"}
          </button>
        </form>
      </div>

      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
          <p className="font-bold">Error</p>
          <p>{error}</p>
        </div>
      )}

      {result && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">Import Results</h2>

          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="bg-green-100 dark:bg-green-900 p-4 rounded">
              <p className="text-sm text-gray-600 dark:text-gray-300">
                Imported
              </p>
              <p className="text-2xl font-bold text-green-700 dark:text-green-300">
                {result.imported}
              </p>
            </div>
            <div className="bg-red-100 dark:bg-red-900 p-4 rounded">
              <p className="text-sm text-gray-600 dark:text-gray-300">
                Failed
              </p>
              <p className="text-2xl font-bold text-red-700 dark:text-red-300">
                {result.failed}
              </p>
            </div>
            <div className="bg-blue-100 dark:bg-blue-900 p-4 rounded">
              <p className="text-sm text-gray-600 dark:text-gray-300">
                Success Rate
              </p>
              <p className="text-2xl font-bold text-blue-700 dark:text-blue-300">
                {result.imported + result.failed > 0
                  ? Math.round(
                      (result.imported / (result.imported + result.failed)) *
                        100
                    )
                  : 0}
                %
              </p>
            </div>
          </div>

          {result.errors.length > 0 && (
            <div>
              <h3 className="font-semibold mb-2">
                Errors ({result.errors.length})
              </h3>
              <div className="bg-gray-100 dark:bg-gray-700 rounded p-4 max-h-96 overflow-y-auto">
                {result.errors.map((err, index) => (
                  <div
                    key={index}
                    className="mb-2 pb-2 border-b border-gray-300 dark:border-gray-600 last:border-0"
                  >
                    <p className="text-sm">
                      {err.line && (
                        <span className="font-semibold">Line {err.line}: </span>
                      )}
                      {err.character && (
                        <span className="font-mono bg-gray-200 dark:bg-gray-600 px-1 rounded">
                          {err.character}
                        </span>
                      )}{" "}
                      - {err.error}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-6 mt-6">
        <h2 className="text-xl font-semibold mb-4">Format Information</h2>

        <div className="space-y-4">
          <div>
            <h3 className="font-semibold mb-2">JSON Format (HSK Vocabulary)</h3>
            <p className="text-sm text-gray-600 dark:text-gray-300 mb-2">
              Source:{" "}
              <a
                href="https://github.com/drkameleon/complete-hsk-vocabulary"
                target="_blank"
                rel="noopener noreferrer"
                className="text-blue-600 hover:underline"
              >
                github.com/drkameleon/complete-hsk-vocabulary
              </a>
            </p>
            <pre className="bg-gray-100 dark:bg-gray-700 p-4 rounded text-sm overflow-x-auto">
              {JSON.stringify(
                {
                  simplified: "爱好",
                  radical: "爫",
                  level: ["new-1", "old-3"],
                  frequency: 4902,
                  pos: ["n", "v"],
                  forms: [
                    {
                      traditional: "愛好",
                      transcriptions: {
                        pinyin: "ài hào",
                        numeric: "ai4 hao4",
                      },
                      meanings: ["to like; hobby"],
                      classifiers: ["个"],
                    },
                  ],
                },
                null,
                2
              )}
            </pre>
          </div>

          <div>
            <h3 className="font-semibold mb-2">CSV Format</h3>
            <pre className="bg-gray-100 dark:bg-gray-700 p-4 rounded text-sm overflow-x-auto">
              {`simplified,traditional,pinyin,meaning,hsk_level,radical,frequency,pos,classifiers
爱好,愛好,ài hào,"to like; hobby","new-1,old-3",爫,4902,"n,v",个`}
            </pre>
          </div>
        </div>
      </div>
    </div>
  )
}
