"use client"

import * as React from "react"
import { useForm, useFieldArray } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { format } from "date-fns"
import { CalendarIcon, Loader2, Trash2, PlusCircle } from "lucide-react"
import { useSession } from "next-auth/react"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Calendar } from "@/components/ui/calendar"
import { Badge } from "@/components/ui/badge"
import { cn } from "@/lib/utils"
import { toast } from "sonner"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import { createPreQuoteRfqAction, previewGeneralRfqCode } from "@/lib/bidding/service"
import { MaterialGroupSelectorDialogSingle } from "@/components/common/material/material-group-selector-dialog-single"
import { MaterialSearchItem } from "@/lib/material/material-group-service"
import { MaterialSelectorDialogSingle } from "@/components/common/selectors/material/material-selector-dialog-single"
import { MaterialSearchItem as SAPMaterialSearchItem } from "@/components/common/selectors/material/material-service"
import { ProcurementManagerSelector } from "@/components/common/selectors/procurement-manager"
import type { ProcurementManagerWithUser } from "@/components/common/selectors/procurement-manager/procurement-manager-service"

// 아이템 스키마
const itemSchema = z.object({
  itemCode: z.string().optional(),
  itemName: z.string().optional(),
  materialCode: z.string().optional(),
  materialName: z.string().optional(),
  quantity: z.number().min(1, "수량은 1 이상이어야 합니다"),
  uom: z.string().min(1, "단위를 입력해주세요"),
  remark: z.string().optional(),
})

// 사전견적용 일반견적 생성 폼 스키마
const createPreQuoteRfqSchema = z.object({
  rfqType: z.string().min(1, "견적 종류를 선택해주세요"),
  rfqTitle: z.string().min(1, "견적명을 입력해주세요"),
  dueDate: z.date({
    required_error: "제출마감일을 선택해주세요",
  }),
  picUserId: z.number().optional(),
  projectId: z.number().optional(),
  remark: z.string().optional(),
  items: z.array(itemSchema).min(1, "최소 하나의 자재를 추가해주세요"),
})

type CreatePreQuoteRfqFormValues = z.infer<typeof createPreQuoteRfqSchema>

interface CreatePreQuoteRfqDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  biddingId: number
  biddingItems: Array<{
    id: number
    materialGroupNumber?: string | null
    materialGroupInfo?: string | null
    materialNumber?: string | null
    materialInfo?: string | null
    quantity?: string | null
    quantityUnit?: string | null
    totalWeight?: string | null
    weightUnit?: string | null
  }>
  picUserId?: number | null
  biddingConditions?: {
    paymentTerms?: string | null
    taxConditions?: string | null
    incoterms?: string | null
    incotermsOption?: string | null
    contractDeliveryDate?: string | null
    shippingPort?: string | null
    destinationPort?: string | null
    isPriceAdjustmentApplicable?: boolean | null
    sparePartOptions?: string | null
  } | null
  onSuccess?: () => void
}

export function CreatePreQuoteRfqDialog({
  open,
  onOpenChange,
  biddingId,
  biddingItems,
  picUserId,
  biddingConditions,
  onSuccess
}: CreatePreQuoteRfqDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [previewCode, setPreviewCode] = React.useState("")
  const [isLoadingPreview, setIsLoadingPreview] = React.useState(false)
  const [selectedManager, setSelectedManager] = React.useState<ProcurementManagerWithUser | undefined>(undefined)
  const { data: session } = useSession()

  const userId = React.useMemo(() => {
    return session?.user?.id ? Number(session.user.id) : null;
  }, [session]);

  // 입찰품목을 일반견적 아이템으로 매핑
  const initialItems = React.useMemo(() => {
    return biddingItems.map((item) => ({
      itemCode: item.materialGroupNumber || "",
      itemName: item.materialGroupInfo || "",
      materialCode: item.materialNumber || "",
      materialName: item.materialInfo || "",
      quantity: item.quantity ? parseFloat(item.quantity) : 1,
      uom: item.quantityUnit || item.weightUnit || "EA",
      remark: "",
    }))
  }, [biddingItems])

  const form = useForm<CreatePreQuoteRfqFormValues>({
    resolver: zodResolver(createPreQuoteRfqSchema),
    defaultValues: {
      rfqType: "",
      rfqTitle: "",
      dueDate: undefined,
      picUserId: undefined,
      projectId: undefined,
      remark: "",
      items: initialItems.length > 0 ? initialItems : [
        {
          itemCode: "",
          itemName: "",
          materialCode: "",
          materialName: "",
          quantity: 1,
          uom: "",
          remark: "",
        },
      ],
    },
  })

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "items",
  })

  // 다이얼로그가 열릴 때 폼 초기화
  React.useEffect(() => {
    if (open) {
      form.reset({
        rfqType: "",
        rfqTitle: "",
        dueDate: undefined,
        picUserId: undefined,
        projectId: undefined,
        remark: "",
        items: initialItems.length > 0 ? initialItems : [
          {
            itemCode: "",
            itemName: "",
            materialCode: "",
            materialName: "",
            quantity: 1,
            uom: "",
            remark: "",
          },
        ],
      })
      setSelectedManager(undefined)
      setPreviewCode("")
    }
  }, [open, initialItems, form])

  // 견적담당자 선택 시 RFQ 코드 미리보기 생성
  React.useEffect(() => {
    if (!selectedManager?.user?.id) {
      setPreviewCode("")
      return
    }

    // 즉시 실행 함수 패턴 사용
    (async () => {
      setIsLoadingPreview(true)
      try {
        const code = await previewGeneralRfqCode(selectedManager.user!.id!)
        setPreviewCode(code)
      } catch (error) {
        console.error("코드 미리보기 오류:", error)
        setPreviewCode("")
      } finally {
        setIsLoadingPreview(false)
      }
    })()
  }, [selectedManager])

  // 견적 종류 변경
  const handleRfqTypeChange = (value: string) => {
    form.setValue("rfqType", value)
  }

  const handleCancel = () => {
    form.reset({
      rfqType: "",
      rfqTitle: "",
      dueDate: undefined,
      picUserId: undefined,
      projectId: undefined,
      remark: "",
      items: initialItems.length > 0 ? initialItems : [
        {
          itemCode: "",
          itemName: "",
          materialCode: "",
          materialName: "",
          quantity: 1,
          uom: "",
          remark: "",
        },
      ],
    })
    setSelectedManager(undefined)
    setPreviewCode("")
    onOpenChange(false)
  }

  const onSubmit = async (data: CreatePreQuoteRfqFormValues) => {
    if (!userId) {
      toast.error("로그인이 필요합니다")
      return
    }

    if (!selectedManager?.user?.id) {
      toast.error("견적담당자를 선택해주세요")
      return
    }

    const picUserId = selectedManager.user.id

    setIsLoading(true)
    
    try {
      // 서버 액션 호출 (입찰 조건 포함)
      const result = await createPreQuoteRfqAction({
        biddingId,
        rfqType: data.rfqType,
        rfqTitle: data.rfqTitle,
        dueDate: data.dueDate,
        picUserId,
        projectId: data.projectId,
        remark: data.remark || "",
        items: data.items as Array<{
          itemCode: string;
          itemName: string;
          materialCode?: string;
          materialName?: string;
          quantity: number;
          uom: string;
          remark?: string;
        }>,
        biddingConditions: biddingConditions || undefined,
        createdBy: userId,
        updatedBy: userId,
      })

      if (result.success) {
        toast.success(result.message, {
          description: result.data?.rfqCode ? `RFQ 코드: ${result.data.rfqCode}` : undefined,
        })

        // 다이얼로그 닫기
        onOpenChange(false)
        
        // 성공 콜백 실행
        if (onSuccess) {
          onSuccess()
        }
      } else {
        toast.error(result.error || "사전견적용 일반견적 생성에 실패했습니다")
      }
      
    } catch (error) {
      console.error('사전견적용 일반견적 생성 오류:', error)
      toast.error("사전견적용 일반견적 생성에 실패했습니다", {
        description: "알 수 없는 오류가 발생했습니다",
      })
    } finally {
      setIsLoading(false)
    }
  }

  // 아이템 추가
  const handleAddItem = () => {
    append({
      itemCode: "",
      itemName: "",
      materialCode: "",
      materialName: "",
      quantity: 1,
      uom: "",
      remark: "",
    })
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl h-[90vh] flex flex-col">
        {/* 고정된 헤더 */}
        <DialogHeader className="flex-shrink-0">
          <DialogTitle>사전견적용 일반견적 생성</DialogTitle>
          <DialogDescription>
            입찰의 사전견적을 위한 일반견적을 생성합니다. 입찰품목이 자재정보로 매핑되어 있습니다.
          </DialogDescription>
        </DialogHeader>

        {/* 스크롤 가능한 컨텐츠 영역 */}
        <ScrollArea className="flex-1 px-1">
          <Form {...form}>
            <form id="createPreQuoteRfqForm" onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 py-2">
              
              {/* 기본 정보 섹션 */}
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">기본 정보</h3>
                
                <div className="grid grid-cols-2 gap-4">
                  {/* 견적 종류 */}
                  <div className="space-y-2">
                    <FormField
                      control={form.control}
                      name="rfqType"
                      render={({ field }) => (
                        <FormItem className="flex flex-col">
                          <FormLabel>
                            견적 종류 <span className="text-red-500">*</span>
                          </FormLabel>
                          <Select onValueChange={handleRfqTypeChange} value={field.value}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="견적 종류 선택" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="단가계약">단가계약</SelectItem>
                              <SelectItem value="매각계약">매각계약</SelectItem>
                              <SelectItem value="일반계약">일반계약</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>

                  {/* 제출마감일 */}
                  <FormField
                    control={form.control}
                    name="dueDate"
                    render={({ field }) => (
                      <FormItem className="flex flex-col">
                        <FormLabel>
                          제출마감일 <span className="text-red-500">*</span>
                        </FormLabel>
                        <Popover>
                          <PopoverTrigger asChild>
                            <FormControl>
                              <Button
                                variant="outline"
                                className={cn(
                                  "w-full pl-3 text-left font-normal",
                                  !field.value && "text-muted-foreground"
                                )}
                              >
                                {field.value ? (
                                  format(field.value, "yyyy-MM-dd")
                                ) : (
                                  <span>제출마감일을 선택하세요</span>
                                )}
                                <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                              </Button>
                            </FormControl>
                          </PopoverTrigger>
                          <PopoverContent className="w-auto p-0" align="start">
                            <Calendar
                              mode="single"
                              selected={field.value}
                              onSelect={field.onChange}
                              disabled={(date) =>
                                date < new Date() || date < new Date("1900-01-01")
                              }
                              initialFocus
                            />
                          </PopoverContent>
                        </Popover>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                {/* 견적명 */}
                <FormField
                  control={form.control}
                  name="rfqTitle"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        견적명 <span className="text-red-500">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input
                          placeholder="예: 입찰 사전견적용 일반견적"
                          {...field}
                        />
                      </FormControl>
                      <FormDescription>
                        견적의 목적이나 내용을 간단명료하게 입력해주세요
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* 프로젝트 선택 */}
                <FormField
                  control={form.control}
                  name="projectId"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>프로젝트</FormLabel>
                      <FormControl>
                        {/* ProjectSelector는 별도 컴포넌트 필요 */}
                        <Input
                          placeholder="프로젝트 ID (선택사항)"
                          type="number"
                          {...field}
                          onChange={(e) => field.onChange(e.target.value ? Number(e.target.value) : undefined)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* 담당자 정보 */}
                <FormField
                  control={form.control}
                  name="picUserId"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>
                        견적담당자 <span className="text-red-500">*</span>
                      </FormLabel>
                      <FormControl>
                        <ProcurementManagerSelector
                          selectedManager={selectedManager}
                          onManagerSelect={(manager) => {
                            setSelectedManager(manager)
                            field.onChange(manager.user?.id)
                          }}
                          placeholder="견적담당자를 선택하세요"
                        />
                      </FormControl>
                      <FormDescription>
                        사전견적용 일반견적의 담당자를 선택합니다
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                {/* RFQ 코드 미리보기 */}
                {previewCode && (
                  <div className="flex items-center gap-2">
                    <Badge variant="secondary" className="font-mono text-sm">
                      예상 RFQ 코드: {previewCode}
                    </Badge>
                    {isLoadingPreview && (
                      <Loader2 className="h-3 w-3 animate-spin" />
                    )}
                  </div>
                )}

                {/* 비고 */}
                <FormField
                  control={form.control}
                  name="remark"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>비고</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="추가 비고사항을 입력하세요"
                          className="resize-none"
                          rows={3}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <Separator />

              {/* 아이템 정보 섹션 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold">자재 정보</h3>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={handleAddItem}
                  >
                    <PlusCircle className="mr-2 h-4 w-4" />
                    자재 추가
                  </Button>
                </div>

                <div className="space-y-3">
                  {fields.map((field, index) => (
                    <div key={field.id} className="border rounded-lg p-3 bg-gray-50/50">
                      <div className="flex items-center justify-between mb-3">
                        <span className="text-sm font-medium text-gray-700">
                          자재 #{index + 1}
                        </span>
                        {fields.length > 1 && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => remove(index)}
                            className="h-6 w-6 p-0 text-destructive hover:text-destructive"
                          >
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        )}
                      </div>
                      
                      {/* 자재그룹 선택 */}
                      <div className="mb-3">
                        <FormLabel className="text-xs">
                          자재그룹(자재그룹명) <span className="text-red-500">*</span>
                        </FormLabel>
                        <div className="mt-1">
                          <MaterialGroupSelectorDialogSingle
                            triggerLabel="자재그룹 선택"
                            selectedMaterial={(() => {
                              const itemCode = form.watch(`items.${index}.itemCode`);
                              const itemName = form.watch(`items.${index}.itemName`);
                              if (itemCode && itemName) {
                                return {
                                  materialGroupCode: itemCode,
                                  materialGroupDescription: itemName,
                                  displayText: `${itemCode} - ${itemName}`
                                } as MaterialSearchItem;
                              }
                              return null;
                            })()}
                            onMaterialSelect={(material) => {
                              form.setValue(`items.${index}.itemCode`, material?.materialGroupCode || '');
                              form.setValue(`items.${index}.itemName`, material?.materialGroupDescription || '');
                            }}
                            placeholder="자재그룹을 검색하세요..."
                            title="자재그룹 선택"
                            description="원하는 자재그룹을 검색하고 선택해주세요."
                            triggerVariant="outline"
                          />
                        </div>
                      </div>

                      {/* 자재코드 선택 */}
                      <div className="mb-3">
                        <FormLabel className="text-xs">
                          자재코드(자재명)
                        </FormLabel>
                        <div className="mt-1">
                          <MaterialSelectorDialogSingle
                            triggerLabel="자재코드 선택"
                            selectedMaterial={(() => {
                              const materialCode = form.watch(`items.${index}.materialCode`);
                              const materialName = form.watch(`items.${index}.materialName`);
                              if (materialCode && materialName) {
                                return {
                                  materialCode: materialCode,
                                  materialName: materialName,
                                  displayText: `${materialCode} - ${materialName}`
                                } as SAPMaterialSearchItem;
                              }
                              return null;
                            })()}
                            onMaterialSelect={(material) => {
                              form.setValue(`items.${index}.materialCode`, material?.materialCode || '');
                              form.setValue(`items.${index}.materialName`, material?.materialName || '');
                            }}
                            placeholder="자재코드를 검색하세요..."
                            title="자재코드 선택"
                            description="원하는 자재코드를 검색하고 선택해주세요."
                            triggerVariant="outline"
                          />
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-3">
                        {/* 수량 */}
                        <FormField
                          control={form.control}
                          name={`items.${index}.quantity`}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel className="text-xs">
                                수량 <span className="text-red-500">*</span>
                              </FormLabel>
                              <FormControl>
                                <Input
                                  type="number"
                                  min="1"
                                  placeholder="1"
                                  className="h-8 text-sm"
                                  {...field}
                                  onChange={(e) => field.onChange(Number(e.target.value))}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        {/* 단위 */}
                        <FormField
                          control={form.control}
                          name={`items.${index}.uom`}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel className="text-xs">
                                단위 <span className="text-red-500">*</span>
                              </FormLabel>
                              <Select onValueChange={field.onChange} value={field.value}>
                                <FormControl>
                                  <SelectTrigger className="h-8 text-sm">
                                    <SelectValue placeholder="단위 선택" />
                                  </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                  <SelectItem value="EA">EA (Each)</SelectItem>
                                  <SelectItem value="KG">KG (Kilogram)</SelectItem>
                                  <SelectItem value="M">M (Meter)</SelectItem>
                                  <SelectItem value="L">L (Liter)</SelectItem>
                                  <SelectItem value="PC">PC (Piece)</SelectItem>
                                  <SelectItem value="BOX">BOX (Box)</SelectItem>
                                  <SelectItem value="SET">SET (Set)</SelectItem>
                                  <SelectItem value="LOT">LOT (Lot)</SelectItem>
                                  <SelectItem value="PCS">PCS (Pieces)</SelectItem>
                                  <SelectItem value="TON">TON (Ton)</SelectItem>
                                  <SelectItem value="G">G (Gram)</SelectItem>
                                  <SelectItem value="ML">ML (Milliliter)</SelectItem>
                                  <SelectItem value="CM">CM (Centimeter)</SelectItem>
                                  <SelectItem value="MM">MM (Millimeter)</SelectItem>
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>

                      {/* 비고 */}
                      <div className="mt-3">
                        <FormField
                          control={form.control}
                          name={`items.${index}.remark`}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel className="text-xs">비고</FormLabel>
                              <FormControl>
                                <Input
                                  placeholder="자재별 비고사항"
                                  className="h-8 text-sm"
                                  {...field}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </form>
          </Form>
        </ScrollArea>

        {/* 고정된 푸터 */}
        <DialogFooter className="flex-shrink-0">
          <Button
            type="button"
            variant="outline"
            onClick={handleCancel}
            disabled={isLoading}
          >
            취소
          </Button>
          <Button
            type="submit"
            form="createPreQuoteRfqForm"
            onClick={form.handleSubmit(onSubmit)}
            disabled={isLoading}
          >
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            {isLoading ? "생성 중..." : "사전견적용 일반견적 생성"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

