"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import { getInitializationFiles } from "@/actions/admin"

interface ProgressData {
  percent: number
  current: number
  total: number
  message: string
}

interface CompleteData {
  imported: number
  collectionsCreated: number
  hanziAddedToCollections: number
}

export default function AdminInitializePage() {
  const [availableFiles, setAvailableFiles] = useState<string[]>([])
  const [selectedFiles, setSelectedFiles] = useState<string[]>([])
  const [cleanData, setCleanData] = useState(false)
  const [loading, setLoading] = useState(false)
  const [progress, setProgress] = useState<ProgressData | null>(null)
  const [result, setResult] = useState<CompleteData | null>(null)
  const [error, setError] = useState<string | null>(null)

  // Load available files on mount
  useEffect(() => {
    const loadFiles = async () => {
      const response = await getInitializationFiles()
      if (response.success && response.data) {
        setAvailableFiles(response.data)
        // Auto-select complete.json if available
        if (response.data.includes("complete.json")) {
          setSelectedFiles(["complete.json"])
        }
      }
    }
    loadFiles()
  }, [])

  // Debug: Log when progress changes
  useEffect(() => {
    if (progress) {
      console.log("Progress state changed in UI:", progress)
    }
  }, [progress])

  const toggleFileSelection = (fileName: string) => {
    setSelectedFiles(prev =>
      prev.includes(fileName)
        ? prev.filter(f => f !== fileName)
        : [...prev, fileName]
    )
  }

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

    if (selectedFiles.length === 0) {
      setError("Please select at least one file")
      return
    }

    setLoading(true)
    setError(null)
    setResult(null)
    setProgress({ percent: 0, current: 0, total: 0, message: "Starting..." })

    try {
      // Create EventSource connection to SSE endpoint
      const response = await fetch("/api/admin/initialize", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ fileNames: selectedFiles, cleanData }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const reader = response.body?.getReader()
      const decoder = new TextDecoder()

      if (!reader) {
        throw new Error("No response body")
      }

      let buffer = ""

      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value, { stream: true })
        console.log("Received chunk:", chunk.substring(0, 100)) // Debug: show first 100 chars

        buffer += chunk
        const lines = buffer.split("\n\n")
        buffer = lines.pop() || ""

        for (const line of lines) {
          if (!line.trim()) continue

          const eventMatch = line.match(/^event: (.+)$/)
          const dataMatch = line.match(/^data: (.+)$/m)

          if (eventMatch && dataMatch) {
            const event = eventMatch[1]
            const data = JSON.parse(dataMatch[1])

            console.log("SSE Event:", event, data) // Debug logging

            if (event === "progress") {
              setProgress({ ...data }) // Create new object to force re-render
              console.log("Updated progress state:", data)
            } else if (event === "complete") {
              setResult(data)
              setProgress({ percent: 100, current: data.imported, total: data.imported, message: "Complete!" })
              setLoading(false)
              console.log("Completed!")
            } else if (event === "error") {
              setError(data.message)
              setLoading(false)
              console.log("Error:", data.message)
            }
          }
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred")
      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">Initialize Database</h1>
        <div className="flex gap-4 text-sm">
          <Link
            href="/admin/import"
            className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
          >
            Import
          </Link>
          <span className="text-blue-600 dark:text-blue-400 font-semibold">Initialize</span>
        </div>
      </div>

      <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-6">
        <h3 className="text-lg font-semibold text-yellow-800 dark:text-yellow-200 mb-2">
          ⚠️ Warning
        </h3>
        <p className="text-yellow-700 dark:text-yellow-300">
          This operation will import all hanzi from the selected files and create HSK level collections.
          {cleanData && (
            <span className="block mt-2 font-semibold">
              With "Clean data" enabled, ALL existing hanzi, collections, and user progress will be PERMANENTLY DELETED before import.
            </span>
          )}
        </p>
      </div>

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

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">
              Select Files (select multiple)
            </label>
            <div className="border border-gray-300 dark:border-gray-600 rounded-md p-3 max-h-64 overflow-y-auto">
              {availableFiles.length === 0 ? (
                <p className="text-sm text-gray-500">No files available in data/initialization/</p>
              ) : (
                <div className="space-y-2">
                  {availableFiles.map(fileName => (
                    <label key={fileName} className="flex items-center hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded cursor-pointer">
                      <input
                        type="checkbox"
                        checked={selectedFiles.includes(fileName)}
                        onChange={() => toggleFileSelection(fileName)}
                        disabled={loading}
                        className="mr-3 h-4 w-4"
                      />
                      <span className="text-sm">{fileName}</span>
                    </label>
                  ))}
                </div>
              )}
            </div>
            {selectedFiles.length > 0 && (
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-2">
                {selectedFiles.length} file(s) selected: {selectedFiles.join(", ")}
              </p>
            )}
          </div>

          <div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={cleanData}
                onChange={(e) => setCleanData(e.target.checked)}
                disabled={loading}
                className="mr-2 h-4 w-4"
              />
              <span className="text-sm font-medium">
                Clean data before import (Delete all existing data)
              </span>
            </label>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1 ml-6">
              Warning: This will delete all hanzi, collections, user progress, and learning sessions
            </p>
          </div>

          <button
            type="submit"
            disabled={loading || selectedFiles.length === 0}
            className={`w-full py-2 px-4 rounded-md font-medium ${
              loading || selectedFiles.length === 0
                ? "bg-gray-300 dark:bg-gray-600 cursor-not-allowed"
                : cleanData
                ? "bg-red-600 hover:bg-red-700 text-white"
                : "bg-blue-600 hover:bg-blue-700 text-white"
            }`}
          >
            {loading ? "Initializing..." : cleanData ? "Clean & Initialize Database" : "Initialize Database"}
          </button>
        </form>
      </div>

      {progress && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6" key={`progress-${progress.percent}-${progress.current}`}>
          <h3 className="text-lg font-semibold mb-4">Progress</h3>
          <div className="space-y-3">
            <div>
              <div className="flex justify-between text-sm mb-1">
                <span>{progress.message}</span>
                <span className="font-semibold">{progress.percent}%</span>
              </div>
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-4 overflow-hidden">
                <div
                  className="bg-blue-600 h-4 rounded-full transition-all duration-300 ease-out"
                  style={{ width: `${progress.percent}%` }}
                  key={progress.percent}
                />
              </div>
            </div>
            {progress.total > 0 && (
              <p className="text-sm text-gray-600 dark:text-gray-400">
                {progress.current.toLocaleString()} / {progress.total.toLocaleString()}
              </p>
            )}
          </div>
        </div>
      )}

      {error && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-6">
          <h3 className="text-lg font-semibold text-red-800 dark:text-red-200 mb-2">
            Error
          </h3>
          <p className="text-red-700 dark:text-red-300">{error}</p>
        </div>
      )}

      {result && (
        <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
          <h3 className="text-lg font-semibold text-green-800 dark:text-green-200 mb-2">
            ✓ Initialization Complete
          </h3>
          <div className="text-green-700 dark:text-green-300 space-y-2">
            <p>
              <strong>Hanzi imported:</strong> {result.imported.toLocaleString()}
            </p>
            <p>
              <strong>Collections created:</strong> {result.collectionsCreated}
            </p>
            <p>
              <strong>Hanzi added to collections:</strong> {result.hanziAddedToCollections.toLocaleString()}
            </p>
          </div>
        </div>
      )}

      <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mt-6">
        <h3 className="text-lg font-semibold text-blue-800 dark:text-blue-200 mb-2">
          How It Works
        </h3>
        <ul className="text-blue-700 dark:text-blue-300 space-y-2 list-disc list-inside">
          <li>Reads hanzi data from selected JSON files in data/initialization/</li>
          <li>Optionally cleans all existing data (hanzi, collections, progress)</li>
          <li>Imports all hanzi with their forms, meanings, and transcriptions</li>
          <li>Creates public collections for each unique HSK level found (e.g., "HSK new-1", "HSK old-3")</li>
          <li>Adds each hanzi to its corresponding level collection(s)</li>
          <li>Shows real-time progress updates during the entire process</li>
        </ul>
      </div>
    </div>
  )
}
