"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import Link from "next/link"
import { getHanzi } from "@/actions/hanzi"
import { getUserCollections } from "@/actions/collections"

type HanziDetail = {
  id: string
  simplified: string
  radical: string | null
  frequency: number | null
  forms: Array<{
    id: string
    traditional: string
    isDefault: boolean
    transcriptions: Array<{
      type: string
      value: string
    }>
    meanings: Array<{
      language: string
      meaning: string
      orderIndex: number
    }>
    classifiers: Array<{
      classifier: string
    }>
  }>
  hskLevels: Array<{
    level: string
  }>
  partsOfSpeech: Array<{
    pos: string
  }>
}

export default function HanziDetailPage() {
  const params = useParams()
  const router = useRouter()
  const hanziId = params.id as string

  const [hanzi, setHanzi] = useState<HanziDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Add to collection state
  const [showAddModal, setShowAddModal] = useState(false)
  const [collections, setCollections] = useState<Array<{ id: string; name: string }>>([])

  useEffect(() => {
    loadHanzi()
  }, [hanziId])

  const loadHanzi = async () => {
    setLoading(true)
    setError(null)

    try {
      const result = await getHanzi(hanziId)
      if (result.success && result.data) {
        setHanzi(result.data)
      } else {
        setError(result.message || "Failed to load hanzi")
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred")
    } finally {
      setLoading(false)
    }
  }

  const handleAddToCollection = async () => {
    const result = await getUserCollections()
    if (result.success && result.data) {
      setCollections(result.data)
      setShowAddModal(true)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <p className="text-gray-600 dark:text-gray-400">Loading...</p>
      </div>
    )
  }

  if (error || !hanzi) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-600 dark:text-red-400 mb-4">{error || "Hanzi not found"}</p>
          <Link href="/hanzi" className="text-blue-600 hover:underline">
            Back to Search
          </Link>
        </div>
      </div>
    )
  }

  const defaultForm = hanzi.forms.find((f) => f.isDefault) || hanzi.forms[0]

  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="/hanzi"
                className="text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
              >
                Search Hanzi
              </Link>
            </div>
          </div>
        </div>
      </nav>

      <main className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-8 mb-8">
          <div className="flex items-start justify-between mb-6">
            <div>
              <div className="text-8xl font-bold text-gray-900 dark:text-white mb-4">
                {hanzi.simplified}
              </div>
              {defaultForm && defaultForm.traditional !== hanzi.simplified && (
                <p className="text-2xl text-gray-600 dark:text-gray-400 mb-2">
                  Traditional: {defaultForm.traditional}
                </p>
              )}
            </div>
            <div className="flex flex-col gap-2">
              {hanzi.hskLevels.map((level) => (
                <span
                  key={level.level}
                  className="text-sm bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 px-3 py-1 rounded text-center"
                >
                  {level.level.toUpperCase()}
                </span>
              ))}
            </div>
          </div>

          <button
            onClick={handleAddToCollection}
            className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700"
          >
            Add to Collection
          </button>
        </div>

        {/* Main Information */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">
          {/* Transcriptions */}
          {defaultForm && defaultForm.transcriptions.length > 0 && (
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h3 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
                Transcriptions
              </h3>
              <div className="space-y-2">
                {defaultForm.transcriptions.map((trans, index) => (
                  <div key={index} className="flex justify-between items-center">
                    <span className="text-sm text-gray-600 dark:text-gray-400 capitalize">
                      {trans.type}:
                    </span>
                    <span className="text-lg font-medium text-gray-900 dark:text-white">
                      {trans.value}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Meanings */}
          {defaultForm && defaultForm.meanings.length > 0 && (
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h3 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
                Meanings
              </h3>
              <ol className="list-decimal list-inside space-y-2">
                {defaultForm.meanings.map((meaning, index) => (
                  <li key={index} className="text-gray-900 dark:text-white">
                    {meaning.meaning}
                    <span className="text-xs text-gray-500 dark:text-gray-400 ml-2">
                      ({meaning.language})
                    </span>
                  </li>
                ))}
              </ol>
            </div>
          )}
        </div>

        {/* Additional Information */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-8">
          {/* Radical & Frequency */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Character Info
            </h3>
            <div className="space-y-2">
              {hanzi.radical && (
                <div>
                  <span className="text-sm text-gray-600 dark:text-gray-400">Radical:</span>
                  <p className="text-lg font-medium text-gray-900 dark:text-white">
                    {hanzi.radical}
                  </p>
                </div>
              )}
              {hanzi.frequency !== null && (
                <div>
                  <span className="text-sm text-gray-600 dark:text-gray-400">Frequency:</span>
                  <p className="text-lg font-medium text-gray-900 dark:text-white">
                    {hanzi.frequency}
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Parts of Speech */}
          {hanzi.partsOfSpeech.length > 0 && (
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                Parts of Speech
              </h3>
              <div className="flex flex-wrap gap-2">
                {hanzi.partsOfSpeech.map((pos, index) => (
                  <span
                    key={index}
                    className="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 px-3 py-1 rounded text-sm"
                  >
                    {pos.pos}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Classifiers */}
          {defaultForm && defaultForm.classifiers.length > 0 && (
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                Classifiers
              </h3>
              <div className="flex flex-wrap gap-2">
                {defaultForm.classifiers.map((classifier, index) => (
                  <span
                    key={index}
                    className="bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200 px-3 py-1 rounded text-lg"
                  >
                    {classifier.classifier}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* All Forms */}
        {hanzi.forms.length > 1 && (
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
              All Forms
            </h3>
            <div className="space-y-6">
              {hanzi.forms.map((form, index) => (
                <div key={form.id} className="border-b border-gray-200 dark:border-gray-700 pb-6 last:border-0 last:pb-0">
                  <div className="flex items-center gap-2 mb-3">
                    <h4 className="text-2xl font-bold text-gray-900 dark:text-white">
                      {form.traditional}
                    </h4>
                    {form.isDefault && (
                      <span className="text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-2 py-1 rounded">
                        Default
                      </span>
                    )}
                  </div>

                  {form.transcriptions.length > 0 && (
                    <div className="mb-3">
                      <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">Transcriptions:</p>
                      <div className="flex flex-wrap gap-2">
                        {form.transcriptions.map((trans, i) => (
                          <span key={i} className="text-sm text-gray-900 dark:text-white">
                            {trans.type}: <strong>{trans.value}</strong>
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {form.meanings.length > 0 && (
                    <div>
                      <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">Meanings:</p>
                      <ol className="list-decimal list-inside text-sm">
                        {form.meanings.map((meaning, i) => (
                          <li key={i} className="text-gray-900 dark:text-white">
                            {meaning.meaning}
                          </li>
                        ))}
                      </ol>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </main>

      {/* Add to Collection Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-xl font-bold text-gray-900 dark:text-white">
                Add to Collection
              </h3>
              <button
                onClick={() => setShowAddModal(false)}
                className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
              >
                ×
              </button>
            </div>

            {collections.length === 0 ? (
              <div className="text-center py-8">
                <p className="text-gray-600 dark:text-gray-400 mb-4">
                  You don't have any collections yet.
                </p>
                <Link
                  href="/collections/new"
                  className="inline-block bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700"
                >
                  Create Collection
                </Link>
              </div>
            ) : (
              <div className="space-y-2 max-h-96 overflow-y-auto">
                {collections.map((collection) => (
                  <button
                    key={collection.id}
                    onClick={() => router.push(`/collections/${collection.id}`)}
                    className="w-full text-left p-3 rounded-lg bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-white"
                  >
                    {collection.name}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
