"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { Loader, Upload, X } from "lucide-react"
import { useRouter } from "next/navigation"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"

import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { updateInformationData } from "@/lib/information/service"
import { updateInformationSchema, type UpdateInformationSchema } from "@/lib/information/validations"
import type { PageInformation } from "@/db/schema/information"

interface UpdateInformationDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  information?: PageInformation
  onSuccess?: () => void
}

export function UpdateInformationDialog({
  open,
  onOpenChange,
  information,
  onSuccess,
}: UpdateInformationDialogProps) {
  const router = useRouter()
  const [isLoading, setIsLoading] = React.useState(false)
  const [uploadedFile, setUploadedFile] = React.useState<File | null>(null)

  const form = useForm<UpdateInformationSchema>({
    resolver: zodResolver(updateInformationSchema),
    defaultValues: {
      id: 0,
      informationContent: "",
      attachmentFileName: "",
      attachmentFilePath: "",
      attachmentFileSize: "",
      isActive: true,
    },
  })

  // 인포메이션 데이터가 변경되면 폼 업데이트
  React.useEffect(() => {
    if (information && open) {
      form.reset({
        id: information.id,
        informationContent: information.informationContent || "",
        attachmentFileName: information.attachmentFileName || "",
        attachmentFilePath: information.attachmentFilePath || "",
        attachmentFileSize: information.attachmentFileSize || "",
        isActive: information.isActive,
      })
    }
  }, [information, open, form])

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      setUploadedFile(file)
      // 파일 크기를 MB 단위로 변환
      const sizeInMB = (file.size / (1024 * 1024)).toFixed(2)
      form.setValue("attachmentFileName", file.name)
      form.setValue("attachmentFileSize", `${sizeInMB} MB`)
    }
  }

  const removeFile = () => {
    setUploadedFile(null)
    form.setValue("attachmentFileName", "")
    form.setValue("attachmentFilePath", "")
    form.setValue("attachmentFileSize", "")
  }

  const uploadFile = async (file: File): Promise<string> => {
    const formData = new FormData()
    formData.append("file", file)

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

    if (!response.ok) {
      throw new Error("파일 업로드에 실패했습니다.")
    }

    const result = await response.json()
    return result.url
  }

  const onSubmit = async (values: UpdateInformationSchema) => {
    setIsLoading(true)
    try {
      const finalValues = { ...values }

      // 새 파일이 있으면 업로드
      if (uploadedFile) {
        const filePath = await uploadFile(uploadedFile)
        finalValues.attachmentFilePath = filePath
      }

      const result = await updateInformationData(finalValues)

      if (result.success) {
        toast.success(result.message)
        if (onSuccess) onSuccess()
        onOpenChange(false)
        router.refresh()
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      toast.error("인포메이션 수정에 실패했습니다.")
      console.error(error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleClose = () => {
    setUploadedFile(null)
    onOpenChange(false)
  }

  const currentFileName = form.watch("attachmentFileName")

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>인포메이션 수정</DialogTitle>
          <DialogDescription>
            페이지 인포메이션 정보를 수정합니다.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="bg-gray-50 p-4 rounded-lg">
              <div className="flex items-center gap-2 mb-2">
                <span className="font-medium">페이지 정보</span>
              </div>
              <div className="text-sm ">
                <div><strong>페이지명:</strong> {information?.pageName}</div>
                <div><strong>경로:</strong> {information?.pagePath}</div>
              </div>
            </div>

            <FormField
              control={form.control}
              name="informationContent"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>인포메이션 내용</FormLabel>
                  <FormControl>
                    <Textarea 
                      placeholder="인포메이션 내용을 입력하세요" 
                      rows={6}
                      {...field} 
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div>
              <FormLabel>첨부파일</FormLabel>
              <div className="mt-2">
                {uploadedFile ? (
                  <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium">{uploadedFile.name}</span>
                      <span className="text-xs text-gray-500">
                        ({(uploadedFile.size / (1024 * 1024)).toFixed(2)} MB)
                      </span>
                      <span className="text-xs">(새 파일)</span>
                    </div>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={removeFile}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ) : currentFileName ? (
                  <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium">{currentFileName}</span>
                      {form.watch("attachmentFileSize") && (
                        <span className="text-xs text-gray-500">
                          ({form.watch("attachmentFileSize")})
                        </span>
                      )}
                    </div>
                    <div className="flex gap-2">
                      <label
                        htmlFor="file-upload-update"
                        className="cursor-pointer text-sm"
                      >
                        변경
                      </label>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={removeFile}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                ) : (
                  <div className="border-2 border-dashed border-gray-300 rounded-lg p-4">
                    <div className="text-center">
                      <Upload className="mx-auto h-8 w-8 text-gray-400" />
                      <div className="mt-2">
                        <label
                          htmlFor="file-upload-update"
                          className="cursor-pointer text-sm"
                        >
                          파일을 선택하세요
                        </label>
                      </div>
                      <p className="text-xs text-gray-500 mt-1">
                        PDF, DOC, DOCX, XLSX, PPT, PPTX, TXT, ZIP 파일만 업로드 가능
                      </p>
                    </div>
                  </div>
                )}
                <input
                  id="file-upload-update"
                  type="file"
                  className="hidden"
                  onChange={handleFileSelect}
                  accept=".pdf,.doc,.docx,.xlsx,.ppt,.pptx,.txt,.zip"
                />
              </div>
            </div>

            <FormField
              control={form.control}
              name="isActive"
              render={({ field }) => (
                <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
                  <div className="space-y-0.5">
                    <FormLabel className="text-base">활성 상태</FormLabel>
                    <div className="text-sm text-muted-foreground">
                      활성화하면 해당 페이지에서 인포메이션 버튼이 표시됩니다.
                    </div>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={handleClose}
                disabled={isLoading}
              >
                취소
              </Button>
              <Button type="submit" disabled={isLoading}>
                {isLoading && <Loader className="mr-2 h-4 w-4 animate-spin" />}
                수정
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
} 