"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { toast } from "sonner"
import { Loader2, Copy } from "lucide-react"
import { duplicateApprovalLine } from "../service"
import { type ApprovalLine } from "../service"
import { useSession } from "next-auth/react"

const duplicateSchema = z.object({
  name: z.string().min(1, "결재선 이름은 필수입니다"),
  description: z.string().optional(),
})

type DuplicateFormData = z.infer<typeof duplicateSchema>

interface DuplicateApprovalLineSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  line: ApprovalLine | null
}

export function DuplicateApprovalLineSheet({
  open,
  onOpenChange,
  line,
}: DuplicateApprovalLineSheetProps) {
  const { data: session } = useSession()
  const [isSubmitting, setIsSubmitting] = React.useState(false)

  const form = useForm<DuplicateFormData>({
    resolver: zodResolver(duplicateSchema),
    defaultValues: {
      name: line ? `${line.name} (복사본)` : "",
      description: line?.description ? `${line.description} (복사본)` : "",
    },
  })

  // line이 변경될 때 폼 초기화
  React.useEffect(() => {
    if (line) {
      form.reset({
        name: `${line.name} (복사본)`,
        description: line.description ? `${line.description} (복사본)` : "",
      })
    }
  }, [line, form])

  const onSubmit = async (data: DuplicateFormData) => {
    if (!line || !session?.user?.id) {
      toast.error("복제할 결재선이 없거나 로그인이 필요합니다.")
      return
    }

    setIsSubmitting(true)

    try {
      const result = await duplicateApprovalLine(
        line.id,
        data.name,
        session.user.id
      )

      if (result.success) {
        toast.success("결재선이 성공적으로 복제되었습니다.")
        form.reset()
        onOpenChange(false)
      } else {
        toast.error(result.error || "복제에 실패했습니다.")
      }
    } catch (error) {
      toast.error("복제 중 오류가 발생했습니다.")
    } finally {
      setIsSubmitting(false)
    }
  }

  if (!line) return null

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent>
        <SheetHeader>
          <SheetTitle className="flex items-center gap-2">
            <Copy className="h-5 w-5" />
            결재선 복제
          </SheetTitle>
          <SheetDescription>
            "{line.name}" 결재선을 복제하여 새로운 결재선을 만듭니다.
          </SheetDescription>
        </SheetHeader>

        <div className="mt-6">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              {/* 원본 정보 표시 */}
              <div className="p-4 bg-gray-50 border rounded-lg">
                <h4 className="font-medium text-sm mb-2">원본 결재선 정보</h4>
                <div className="space-y-2 text-sm">
                  <div>
                    <span className="font-medium">이름:</span> {line.name}
                  </div>
                  {line.description && (
                    <div>
                      <span className="font-medium">설명:</span> {line.description}
                    </div>
                  )}
                  <div>
                    <span className="font-medium">결재자:</span> {(line.aplns as any[])?.length || 0}명
                  </div>
                </div>
              </div>

              {/* 새 결재선 정보 */}
              <div className="space-y-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>새 결재선 이름 *</FormLabel>
                      <FormControl>
                        <Input placeholder="새 결재선 이름을 입력하세요" {...field} />
                      </FormControl>
                      <FormDescription>
                        원본과 구분할 수 있는 이름을 입력하세요.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>설명</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="새 결재선에 대한 설명을 입력하세요"
                          {...field}
                        />
                      </FormControl>
                      <FormDescription>
                        선택사항입니다. 결재선의 용도나 특징을 설명할 수 있습니다.
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {/* 제출 버튼 */}
              <div className="flex justify-end space-x-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => onOpenChange(false)}
                  disabled={isSubmitting}
                >
                  취소
                </Button>
                <Button type="submit" disabled={isSubmitting}>
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      복제 중...
                    </>
                  ) : (
                    <>
                      <Copy className="w-4 h-4 mr-2" />
                      결재선 복제
                    </>
                  )}
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </SheetContent>
    </Sheet>
  )
} 