"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { createCollection, createCollectionWithHanzi, parseHanziList } from "@/actions/collections"

type Tab = "empty" | "fromList"

export default function NewCollectionPage() {
  const router = useRouter()
  const [activeTab, setActiveTab] = useState<Tab>("empty")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Form state
  const [name, setName] = useState("")
  const [description, setDescription] = useState("")
  const [isPublic, setIsPublic] = useState(false)
  const [hanziList, setHanziList] = useState("")

  // Parse state
  const [parseResult, setParseResult] = useState<{
    valid: boolean
    found: Array<{ id: string; simplified: string; pinyin: string | null }>
    notFound: string[]
    duplicates: string[]
  } | null>(null)

  const handleParseList = async () => {
    if (!hanziList.trim()) {
      setError("Please enter hanzi list")
      return
    }

    setLoading(true)
    setError(null)

    try {
      const result = await parseHanziList(hanziList)
      if (result.success && result.data) {
        setParseResult(result.data)
        if (!result.data.valid) {
          setError(`${result.data.notFound.length} hanzi not found in database`)
        }
      } else {
        setError(result.message || "Failed to parse hanzi list")
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred")
    } finally {
      setLoading(false)
    }
  }

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

    if (!name.trim()) {
      setError("Name is required")
      return
    }

    setLoading(true)
    setError(null)

    try {
      const result = await createCollection(name, description || undefined, isPublic)

      if (result.success && result.data) {
        router.push(`/collections/${result.data.id}`)
      } else {
        setError(result.message || "Failed to create collection")
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred")
    } finally {
      setLoading(false)
    }
  }

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

    if (!name.trim()) {
      setError("Name is required")
      return
    }

    if (!hanziList.trim()) {
      setError("Hanzi list is required")
      return
    }

    if (!parseResult || !parseResult.valid) {
      setError("Please preview and fix any errors in the hanzi list first")
      return
    }

    setLoading(true)
    setError(null)

    try {
      const result = await createCollectionWithHanzi(
        name,
        description || undefined,
        isPublic,
        hanziList
      )

      if (result.success && result.data) {
        router.push(`/collections/${result.data.id}`)
      } else {
        setError(result.message || "Failed to create collection")
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      <nav className="bg-white dark:bg-gray-800 shadow">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16 items-center">
            <div className="flex items-center space-x-8">
              <Link href="/dashboard">
                <h1 className="text-xl font-bold text-gray-900 dark:text-white cursor-pointer">
                  MemoHanzi <span className="text-sm font-normal text-gray-500">记汉字</span>
                </h1>
              </Link>
              <Link
                href="/collections"
                className="text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
              >
                Collections
              </Link>
            </div>
          </div>
        </div>
      </nav>

      <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            Create Collection
          </h2>
          <p className="text-gray-600 dark:text-gray-400">
            Create a new collection to organize your hanzi
          </p>
        </div>

        {/* Tabs */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
          <div className="border-b border-gray-200 dark:border-gray-700">
            <div className="flex">
              <button
                onClick={() => setActiveTab("empty")}
                className={`flex-1 py-4 px-6 text-center font-medium ${
                  activeTab === "empty"
                    ? "border-b-2 border-blue-600 text-blue-600 dark:text-blue-400"
                    : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
                }`}
              >
                Empty Collection
              </button>
              <button
                onClick={() => setActiveTab("fromList")}
                className={`flex-1 py-4 px-6 text-center font-medium ${
                  activeTab === "fromList"
                    ? "border-b-2 border-blue-600 text-blue-600 dark:text-blue-400"
                    : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
                }`}
              >
                From List
              </button>
            </div>
          </div>

          <div className="p-6">
            {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>
            )}

            {activeTab === "empty" ? (
              <form onSubmit={handleCreateEmpty} className="space-y-6">
                <div>
                  <label className="block text-sm font-medium mb-2 text-gray-900 dark:text-white">
                    Collection Name *
                  </label>
                  <input
                    type="text"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="e.g., My First 100 Characters"
                    className="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    disabled={loading}
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2 text-gray-900 dark:text-white">
                    Description (optional)
                  </label>
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Brief description of this collection..."
                    rows={3}
                    className="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    disabled={loading}
                  />
                </div>

                <div>
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={isPublic}
                      onChange={(e) => setIsPublic(e.target.checked)}
                      className="mr-2"
                      disabled={loading}
                    />
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      Make this collection public
                    </span>
                  </label>
                  <p className="text-xs text-gray-600 dark:text-gray-400 mt-1 ml-6">
                    Public collections can be viewed by other users
                  </p>
                </div>

                <div className="flex gap-4">
                  <button
                    type="submit"
                    disabled={loading}
                    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 ? "Creating..." : "Create Collection"}
                  </button>
                  <Link
                    href="/collections"
                    className="bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-white px-6 py-2 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600"
                  >
                    Cancel
                  </Link>
                </div>
              </form>
            ) : (
              <form onSubmit={handleCreateWithHanzi} className="space-y-6">
                <div>
                  <label className="block text-sm font-medium mb-2 text-gray-900 dark:text-white">
                    Collection Name *
                  </label>
                  <input
                    type="text"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="e.g., HSK 1 Vocabulary"
                    className="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    disabled={loading}
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2 text-gray-900 dark:text-white">
                    Description (optional)
                  </label>
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Brief description of this collection..."
                    rows={2}
                    className="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    disabled={loading}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-2 text-gray-900 dark:text-white">
                    Hanzi List *
                  </label>
                  <textarea
                    value={hanziList}
                    onChange={(e) => {
                      setHanziList(e.target.value)
                      setParseResult(null)
                      setError(null)
                    }}
                    placeholder="Paste hanzi here (newline, comma, or space separated)&#10;Example: 好 爱 你&#10;or: 好, 爱, 你&#10;or: 好&#10;爱&#10;你"
                    rows={6}
                    className="block w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white font-mono text-sm"
                    disabled={loading}
                    required
                  />
                  <button
                    type="button"
                    onClick={handleParseList}
                    disabled={loading || !hanziList.trim()}
                    className="mt-2 bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
                  >
                    {loading ? "Parsing..." : "Preview"}
                  </button>
                </div>

                {parseResult && (
                  <div className="bg-gray-100 dark:bg-gray-700 rounded-lg p-4">
                    <h4 className="font-semibold mb-3 text-gray-900 dark:text-white">
                      Preview Results
                    </h4>

                    {parseResult.found.length > 0 && (
                      <div className="mb-3">
                        <p className="text-sm font-medium text-green-700 dark:text-green-400 mb-2">
                          ✓ Found: {parseResult.found.length} hanzi
                        </p>
                        <div className="flex flex-wrap gap-2">
                          {parseResult.found.slice(0, 20).map((h) => (
                            <span
                              key={h.id}
                              className="bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 px-2 py-1 rounded text-sm"
                            >
                              {h.simplified} {h.pinyin ? `(${h.pinyin})` : ""}
                            </span>
                          ))}
                          {parseResult.found.length > 20 && (
                            <span className="text-gray-600 dark:text-gray-400 text-sm">
                              ... and {parseResult.found.length - 20} more
                            </span>
                          )}
                        </div>
                      </div>
                    )}

                    {parseResult.notFound.length > 0 && (
                      <div className="mb-3">
                        <p className="text-sm font-medium text-red-700 dark:text-red-400 mb-2">
                          ✗ Not found: {parseResult.notFound.length} hanzi
                        </p>
                        <div className="flex flex-wrap gap-2">
                          {parseResult.notFound.map((char, i) => (
                            <span
                              key={i}
                              className="bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 px-2 py-1 rounded text-sm"
                            >
                              {char}
                            </span>
                          ))}
                        </div>
                        <p className="text-xs text-red-600 dark:text-red-400 mt-2">
                          All hanzi must exist in the database. Please remove or correct these.
                        </p>
                      </div>
                    )}

                    {parseResult.duplicates.length > 0 && (
                      <div>
                        <p className="text-sm font-medium text-yellow-700 dark:text-yellow-400 mb-2">
                          ⚠ Duplicates in input: {parseResult.duplicates.length}
                        </p>
                        <div className="flex flex-wrap gap-2">
                          {parseResult.duplicates.map((char, i) => (
                            <span
                              key={i}
                              className="bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 px-2 py-1 rounded text-sm"
                            >
                              {char}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}

                <div>
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={isPublic}
                      onChange={(e) => setIsPublic(e.target.checked)}
                      className="mr-2"
                      disabled={loading}
                    />
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      Make this collection public
                    </span>
                  </label>
                  <p className="text-xs text-gray-600 dark:text-gray-400 mt-1 ml-6">
                    Public collections can be viewed by other users
                  </p>
                </div>

                <div className="flex gap-4">
                  <button
                    type="submit"
                    disabled={loading || !parseResult || !parseResult.valid}
                    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 ? "Creating..." : `Create with ${parseResult?.found.length || 0} Hanzi`}
                  </button>
                  <Link
                    href="/collections"
                    className="bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-white px-6 py-2 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600"
                  >
                    Cancel
                  </Link>
                </div>
              </form>
            )}
          </div>
        </div>

        {/* Help Section */}
        <div className="mt-6 bg-blue-50 dark:bg-blue-900/20 rounded-lg p-6">
          <h3 className="font-semibold text-blue-900 dark:text-blue-300 mb-2">Tips</h3>
          <ul className="text-sm text-blue-800 dark:text-blue-400 space-y-1 list-disc list-inside">
            <li>
              <strong>Empty Collection:</strong> Create an empty collection and add hanzi later
            </li>
            <li>
              <strong>From List:</strong> Create a collection with hanzi from a pasted list
            </li>
            <li>Supports both single characters (好) and multi-character words (中国)</li>
            <li>List can be newline, comma, or space separated</li>
            <li>All hanzi must exist in the database (use import to add new hanzi first)</li>
          </ul>
        </div>
      </main>
    </div>
  )
}
