"use client"

import type React from "react"

import { useState } from "react"
import { Upload, FileText, Languages, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Label } from "@/components/ui/label"

const LANGUAGES = [
  { code: "zh-TW", name: "繁體中文" },
  { code: "zh-CN", name: "簡體中文" },
  { code: "en", name: "English" },
  { code: "ja", name: "日本語" },
  { code: "ko", name: "한국어" },
  { code: "es", name: "Español" },
  { code: "fr", name: "Français" },
  { code: "de", name: "Deutsch" },
  { code: "it", name: "Italiano" },
  { code: "pt", name: "Português" },
  { code: "ru", name: "Русский" },
  { code: "ar", name: "العربية" },
  { code: "th", name: "ไทย" },
  { code: "vi", name: "Tiếng Việt" },
]

export function PDFTranslator() {
  const [file, setFile] = useState<File | null>(null)
  const [targetLanguage, setTargetLanguage] = useState<string>("")
  const [isTranslating, setIsTranslating] = useState(false)
  const [translatedText, setTranslatedText] = useState<string>("")
  const [isDragging, setIsDragging] = useState(false)

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0]
    if (selectedFile && selectedFile.type === "application/pdf") {
      setFile(selectedFile)
      setTranslatedText("")
    } else {
      alert("請選擇PDF文件")
    }
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(true)
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    const droppedFile = e.dataTransfer.files[0]
    if (droppedFile && droppedFile.type === "application/pdf") {
      setFile(droppedFile)
      setTranslatedText("")
    } else {
      alert("請選擇PDF文件")
    }
  }

  const handleTranslate = async () => {
    if (!file || !targetLanguage) {
      alert("請上傳PDF文件並選擇目標語言")
      return
    }

    setIsTranslating(true)
    setTranslatedText("")

    try {
      const formData = new FormData()
      formData.append("file", file)
      formData.append("targetLanguage", targetLanguage)

      const response = await fetch("/api/translate", {
        method: "POST",
        body: formData,
      })

      if (!response.ok) {
        throw new Error("翻譯失敗")
      }

      const data = await response.json()
      setTranslatedText(data.translatedText)
    } catch (error) {
      console.error("翻譯錯誤:", error)
      alert("翻譯過程中發生錯誤，請稍後再試")
    } finally {
      setIsTranslating(false)
    }
  }

  return (
    <div className="space-y-8">
      {/* Step 1: Upload File */}
      <Card className="border-4 border-primary p-8">
        <div className="space-y-6">
          <div>
            <h2 className="text-2xl font-bold text-foreground mb-2 uppercase tracking-wide">步驟 1: 上傳文件</h2>
            <p className="text-foreground/80">請上傳您想要翻譯的PDF文件</p>
          </div>

          <div className="space-y-4">
            <div className="flex gap-4">
              <div className="flex-1">
                <Label htmlFor="file-upload" className="block w-full cursor-pointer">
                  <div className="border-4 border-primary bg-card hover:bg-secondary transition-colors p-6 text-center">
                    <Upload className="w-8 h-8 mx-auto mb-2 text-primary" />
                    <span className="text-foreground font-semibold">{file ? file.name : "選擇文件"}</span>
                  </div>
                </Label>
                <input id="file-upload" type="file" accept=".pdf" onChange={handleFileChange} className="hidden" />
              </div>
            </div>

            <div
              onDragOver={handleDragOver}
              onDragLeave={handleDragLeave}
              onDrop={handleDrop}
              className={`border-4 border-primary bg-card p-8 text-center transition-colors ${
                isDragging ? "bg-secondary" : ""
              }`}
            >
              <FileText className="w-12 h-12 mx-auto mb-3 text-primary" />
              <p className="text-foreground font-semibold">拖放PDF文件到這裡</p>
            </div>
          </div>
        </div>
      </Card>

      {/* Step 2: Select Language */}
      <Card className="border-4 border-primary p-8">
        <div className="space-y-6">
          <div>
            <h2 className="text-2xl font-bold text-foreground mb-2 uppercase tracking-wide">步驟 2: 選擇目標語言</h2>
            <p className="text-foreground/80">選擇您想要翻譯成的語言</p>
          </div>

          <div className="space-y-4">
            <div>
              <Label htmlFor="language" className="text-foreground font-bold uppercase text-sm mb-2 block">
                目標語言:
              </Label>
              <Select value={targetLanguage} onValueChange={setTargetLanguage}>
                <SelectTrigger
                  id="language"
                  className="border-4 border-primary bg-card text-foreground font-semibold h-14"
                >
                  <SelectValue placeholder="選擇語言" />
                </SelectTrigger>
                <SelectContent>
                  {LANGUAGES.map((lang) => (
                    <SelectItem key={lang.code} value={lang.code}>
                      <div className="flex items-center gap-2">
                        <Languages className="w-4 h-4" />
                        {lang.name}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <Button
              onClick={handleTranslate}
              disabled={!file || !targetLanguage || isTranslating}
              className="w-full h-14 text-lg font-bold bg-accent hover:bg-accent/90 text-accent-foreground"
            >
              {isTranslating ? (
                <>
                  <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                  翻譯中...
                </>
              ) : (
                "開始翻譯"
              )}
            </Button>
          </div>
        </div>
      </Card>

      {/* Step 3: Translation Result */}
      {translatedText && (
        <Card className="border-4 border-primary p-8">
          <div className="space-y-6">
            <div>
              <h2 className="text-2xl font-bold text-foreground mb-2 uppercase tracking-wide">步驟 3: 翻譯結果</h2>
              <p className="text-foreground/80">您的文件已成功翻譯</p>
            </div>

            <div className="bg-card border-4 border-primary p-6 max-h-96 overflow-y-auto">
              <pre className="whitespace-pre-wrap text-foreground font-sans leading-relaxed">{translatedText}</pre>
            </div>

            <Button
              onClick={() => {
                const blob = new Blob([translatedText], { type: "text/plain" })
                const url = URL.createObjectURL(blob)
                const a = document.createElement("a")
                a.href = url
                a.download = `translated-${file?.name.replace(".pdf", ".txt")}`
                a.click()
                URL.revokeObjectURL(url)
              }}
              className="w-full h-14 text-lg font-bold bg-accent hover:bg-accent/90 text-accent-foreground"
            >
              下載翻譯文本
            </Button>
          </div>
        </Card>
      )}
    </div>
  )
}
