"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm, useFieldArray } from "react-hook-form"
import { toast } from "sonner"
import { Loader, Download, X, FileText } from "lucide-react"
import { useRouter, useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"
import { z } from "zod"

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 { 
  Dropzone,
  DropzoneZone,
  DropzoneInput,
  DropzoneUploadIcon,
  DropzoneTitle,
  DropzoneDescription,
} from "@/components/ui/dropzone"

import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { 
  updateInformationData, 
  uploadInformationAttachment, 
  deleteInformationAttachmentAction,
  downloadInformationAttachment 
} from "@/lib/information/service"
import type { PageInformation, InformationAttachment } from "@/db/schema/information"
// downloadFile은 동적으로 import
import prettyBytes from "pretty-bytes"
import { useSession } from "next-auth/react"

const MAX_FILE_SIZE = 50 * 1024 * 1024 // 50MB

// 폼 스키마
const updateInformationSchema = z.object({
  id: z.number(),
  informationContent: z.string().min(1, "안내사항 내용을 입력해주세요"),
  isActive: z.boolean(),
  newFiles: z.array(z.any()).optional(),
})

type UpdateInformationSchema = z.infer<typeof updateInformationSchema>

interface UpdateInformationDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  information?: PageInformation & { attachments?: InformationAttachment[] }
  onSuccess?: () => void
}

export function UpdateInformationDialog({
  open,
  onOpenChange,
  information,
  onSuccess,
}: UpdateInformationDialogProps) {
  const router = useRouter()
  const params = useParams()
  const lng = (params?.lng as string) || 'ko'
  const { t } = useTranslation(lng, 'common')
  const [isLoading, setIsLoading] = React.useState(false)
  const [isUploadingFiles, setIsUploadingFiles] = React.useState(false)
  const [existingAttachments, setExistingAttachments] = React.useState<InformationAttachment[]>([])
  const session = useSession()
  const userId = session.data?.user?.id

  const form = useForm<UpdateInformationSchema>({
    resolver: zodResolver(updateInformationSchema),
    defaultValues: {
      id: 0,
      informationContent: "",
      isActive: true,
      newFiles: [],
    },
  })

  const { fields: newFileFields, append: appendFile, remove: removeFile } = useFieldArray({
    control: form.control,
    name: "newFiles",
  })

  // 안내사항 데이터가 변경되면 폼 업데이트
  React.useEffect(() => {
    if (information && open) {
      form.reset({
        id: information.id,
        informationContent: information.informationContent || "",
        isActive: information.isActive,
        newFiles: [],
      })
      setExistingAttachments(information.attachments || [])
    }
  }, [information, open, form])

  // 파일 드롭 핸들러
  const handleDropAccepted = React.useCallback((acceptedFiles: File[]) => {
    acceptedFiles.forEach(file => {
      appendFile(file)
    })
  }, [appendFile])

  const handleDropRejected = React.useCallback((rejectedFiles: any[]) => {
    rejectedFiles.forEach(rejection => {
      toast.error(`파일 업로드 실패: ${rejection.file.name}`)
    })
  }, [])

  // 기존 첨부파일 다운로드
  const handleDownloadAttachment = async (attachment: InformationAttachment) => {
    try {
      const result = await downloadInformationAttachment(attachment.id)
      if (result.success && result.data) {
        // 동적으로 downloadFile 함수 import
        const { downloadFile } = await import('@/lib/file-download')
        await downloadFile(result.data.filePath, result.data.fileName)
        toast.success("파일 다운로드가 시작되었습니다.")
      } else {
        toast.error(result.message || "파일 다운로드에 실패했습니다.")
      }
    } catch (error) {
      console.error("파일 다운로드 오류:", error)
      toast.error("파일 다운로드 중 오류가 발생했습니다.")
    }
  }

  // 기존 첨부파일 삭제
  const handleDeleteAttachment = async (attachmentId: number) => {
    if (!confirm("정말로 이 첨부파일을 삭제하시겠습니까?")) return

    try {
      const result = await deleteInformationAttachmentAction(attachmentId)
      if (result.success) {
        setExistingAttachments(prev => prev.filter(att => att.id !== attachmentId))
        toast.success(result.message)
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      console.error("첨부파일 삭제 오류:", error)
      toast.error("첨부파일 삭제 중 오류가 발생했습니다.")
    }
  }

  const onSubmit = async (values: UpdateInformationSchema) => {
    setIsLoading(true)
    try {
      // 1. 안내사항 정보 업데이트
      const updateResult = await updateInformationData({
        id: values.id,
        informationContent: values.informationContent,
        isActive: values.isActive,
      }, userId)  

      if (!updateResult.success) {
        toast.error(updateResult.message)
        return
      }

      // 2. 새 첨부파일 업로드
      if (values.newFiles && values.newFiles.length > 0) {
        setIsUploadingFiles(true)
        
        for (const file of values.newFiles) {
          const formData = new FormData()
          formData.append("informationId", String(values.id))
          formData.append("file", file)
          
          const uploadResult = await uploadInformationAttachment(formData)
          if (!uploadResult.success) {
            toast.error(`파일 업로드 실패: ${file.name} - ${uploadResult.message}`)
          }
        }
        setIsUploadingFiles(false)
      }

      toast.success("안내사항이 성공적으로 수정되었습니다.")
      if (onSuccess) onSuccess()
      onOpenChange(false)
      router.refresh()
    } catch (error) {
      console.error("안내사항 수정 오류:", error)
      toast.error("안내사항 수정에 실패했습니다.")
    } finally {
      setIsLoading(false)
      setIsUploadingFiles(false)
    }
  }

  const handleClose = () => {
    form.reset()
    setExistingAttachments([])
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{t('information.edit.title', '안내사항 수정')}</DialogTitle>
          <DialogDescription>
            {t('information.edit.description', '페이지 안내사항 정보를 수정합니다.')}
          </DialogDescription>
        </DialogHeader>

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

            {/* 인포메이션 내용 */}
            <FormField
              control={form.control}
              name="informationContent"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('information.content.label', '안내사항')}</FormLabel>
                  <FormControl>
                    <Textarea 
                      placeholder={t('information.content.placeholder', '안내사항을 입력하세요')} 
                      rows={6}
                      {...field} 
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 기존 첨부파일 */}
            {existingAttachments.length > 0 && (
              <div className="space-y-3">
                <FormLabel>{t('information.attachment.existing', '기존 첨부파일')}</FormLabel>
                <div className="grid gap-2">
                  {existingAttachments.map((attachment) => (
                    <div key={attachment.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <div className="flex items-center gap-2">
                        <FileText className="h-4 w-4" />
                        <span className="text-sm font-medium">{attachment.fileName}</span>
                        <span className="text-xs text-gray-500">({attachment.fileSize})</span>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDownloadAttachment(attachment)}
                        >
                          <Download className="h-4 w-4" />
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteAttachment(attachment.id)}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* 새 첨부파일 업로드 */}
            <div className="space-y-3">
              <FormLabel>{t('information.attachment.new', '새 첨부파일')}</FormLabel>
              
              <Dropzone
                maxSize={MAX_FILE_SIZE}
                multiple
                onDropAccepted={handleDropAccepted}
                onDropRejected={handleDropRejected}
                disabled={isLoading || isUploadingFiles}
              >
                {({ maxSize }) => (
                  <DropzoneZone className="flex justify-center">
                    <DropzoneInput />
                    <div className="flex items-center gap-6">
                      <DropzoneUploadIcon />
                      <div className="grid gap-0.5">
                        <DropzoneTitle>
                          {t('information.attachment.select', '파일을 선택하세요')}
                        </DropzoneTitle>
                        <DropzoneDescription>
                          드래그 앤 드롭하거나 클릭하여 파일을 선택하세요
                          {maxSize && ` (최대: ${prettyBytes(maxSize)})`}
                        </DropzoneDescription>
                      </div>
                    </div>
                  </DropzoneZone>
                )}
              </Dropzone>

              {/* 새로 선택된 파일 목록 */}
              {newFileFields.length > 0 && (
                <div className="grid gap-2">
                  {newFileFields.map((field, index) => {
                    const file = form.getValues(`newFiles.${index}`)
                    if (!file) return null
                    
                    return (
                      <div key={field.id} className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                        <div className="flex items-center gap-2">
                          <FileText className="h-4 w-4" />
                          <span className="text-sm font-medium">{file.name}</span>
                          <span className="text-xs text-gray-500">({prettyBytes(file.size)})</span>
                          <span className="text-xs text-blue-600">({t('information.attachment.new', '새 파일')})</span>
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => removeFile(index)}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    )
                  })}
                </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">{t('information.status.label', '활성 상태')}</FormLabel>
                    <div className="text-sm text-muted-foreground">
                      {t('information.status.description', '활성화하면 해당 페이지에서 안내사항 버튼이 표시됩니다.')}
                    </div>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={handleClose}
                disabled={isLoading || isUploadingFiles}
              >
                {t('common.cancel', '취소')}
              </Button>
              <Button type="submit" disabled={isLoading || isUploadingFiles}>
                {(isLoading || isUploadingFiles) && <Loader className="mr-2 h-4 w-4 animate-spin" />}
                {isUploadingFiles ? "파일 업로드 중..." : t('common.save', '수정')}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}