"use client";
import * as React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { format } from "date-fns";
import { ko } from "date-fns/locale/ko";
import { toast } from "sonner";
import { Loader2, CalendarIcon } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetFooter, SheetClose } from "@/components/ui/sheet";
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { cn } from "@/lib/utils";
import { updateTechSalesRfq, getTechSalesRfqById } from "@/lib/techsales-rfq/service";
import { getProjectSeriesForProject } from "@/lib/bidding-projects/service";
import { type ProjectSeries } from "@/db/schema/projects";

// Zod schema for form validation
const updateRfqSchema = z.object({
  rfqId: z.number().min(1, "RFQ ID is required"),
  description: z.string(),
  remark: z.string(),
  dueDate: z.string(),
});

type UpdateRfqSchema = z.infer<typeof updateRfqSchema>;

interface UpdateSheetProps {
  open: boolean;
  onOpenChange?: (open: boolean) => void;
  rfqId: number;
  onUpdated?: () => void;
}

export default function UpdateSheet({ open, onOpenChange, rfqId, onUpdated }: UpdateSheetProps) {
  const [isPending, startTransition] = React.useTransition();
  const [projectInfo, setProjectInfo] = React.useState({
    projNm: "",
    sector: "",
    projMsrm: "",
    ptypeNm: "",
    rfqNo: "",
    pspid: "",
  });
  const [rfqInfo, setRfqInfo] = React.useState({
    status: "",
    createdAt: "",
    updatedAt: "",
    createdByName: "",
    updatedByName: "",
    sentByName: "",
    rfqSendDate: "",
  });
  const [seriesInfo, setSeriesInfo] = React.useState<ProjectSeries[]>([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [isLoadingSeries, setIsLoadingSeries] = React.useState(false);

  // K/L 날짜를 4분기로 변환하는 함수
  const convertKLToQuarter = React.useCallback((klDate: string | null): string => {
    if (!klDate) return "정보 없음"

    try {
      // YYYYMMDD 형식의 날짜를 파싱
      const year = parseInt(klDate.substring(0, 4))
      const month = parseInt(klDate.substring(4, 6))

      // 4분기 계산 (1-3월: 1Q, 4-6월: 2Q, 7-9월: 3Q, 10-12월: 4Q)
      const quarter = Math.ceil(month / 3)

      return `${year} ${quarter}Q`
    } catch (error) {
      console.error("K/L 날짜 변환 오류:", error)
      return "날짜 오류"
    }
  }, [])

  // Initialize form with React Hook Form and Zod
  const form = useForm<UpdateRfqSchema>({
    resolver: zodResolver(updateRfqSchema),
    defaultValues: {
      rfqId,
      description: "",
      remark: "",
      dueDate: "",
    },
  });

  // Load RFQ data when sheet opens
  React.useEffect(() => {
    if (open && rfqId) {
      loadRfqData();
    }
  }, [open, rfqId]);

  const loadRfqData = async () => {
    try {
      setIsLoading(true);
      const result = await getTechSalesRfqById(rfqId);
      if (result.error) {
        toast.error(result.error);
        onOpenChange?.(false);
        return;
      }
      if (result.data) {
        form.reset({
          rfqId,
          description: result.data.description || "",
          remark: result.data.remark || "",
          dueDate: result.data.dueDate ? new Date(result.data.dueDate).toISOString().slice(0, 10) : "",
        });
        const pspid = result.data.project[0].pspid || "";
        setProjectInfo({
          projNm: result.data.project[0].projectName || "",
          sector: result.data.project[0].pjtType || "",
          projMsrm: result.data.project[0].projMsrm || "",
          ptypeNm: result.data.project[0].ptypeNm || "",
          rfqNo: result.data.rfqCode || "",
          pspid: pspid,
        });
        setRfqInfo({
          status: result.data.status || "",
          createdAt: result.data.createdAt ? format(new Date(result.data.createdAt), "yyyy-MM-dd HH:mm") : "",
          updatedAt: result.data.updatedAt ? format(new Date(result.data.updatedAt), "yyyy-MM-dd HH:mm") : "",
          createdByName: (result.data as any).createdByName || (result.data as any).createdBy || "",
          updatedByName: (result.data as any).updatedByName || (result.data as any).updatedBy || "",
          sentByName: (result.data as any).sentByName || (result.data as any).sentBy || "",
          rfqSendDate: result.data.rfqSendDate ? format(new Date(result.data.rfqSendDate), "yyyy-MM-dd HH:mm") : "",
        });

        // 시리즈 정보 로드
        if (pspid) {
          setIsLoadingSeries(true);
          try {
            const seriesResult = await getProjectSeriesForProject(pspid);
            setSeriesInfo(seriesResult);
          } catch (error) {
            console.error("시리즈 정보 로드 오류:", error);
            setSeriesInfo([]);
          } finally {
            setIsLoadingSeries(false);
          }
        } else {
          setSeriesInfo([]);
        }
      }
    } catch (error: any) {
      toast.error("RFQ 정보를 불러오는 중 오류가 발생했습니다: " + error.message);
      onOpenChange?.(false);
    } finally {
      setIsLoading(false);
    }
  };

  // Form submission handler with debug logs
  async function onSubmit(values: UpdateRfqSchema) {
    console.log("Form submitted with values:", values);
    startTransition(async () => {
      try {
        console.log("Submitting RFQ update for ID:", values.rfqId);
        const result = await updateTechSalesRfq({
          id: values.rfqId,
          description: values.description,
          remark: values.remark,
          dueDate: new Date(values.dueDate),
          updatedBy: 1, // Replace with actual user ID
        });
        if (result.error) {
          console.error("Update error:", result.error);
          toast.error(result.error);
        } else {
          console.log("RFQ updated successfully");
          toast.success("RFQ가 성공적으로 업데이트되었습니다!");
          onUpdated?.();
          onOpenChange?.(false);
          form.reset();
        }
      } catch (error: any) {
        console.error("Update failed with error:", error.message);
        toast.error("업데이트 중 오류 발생: " + error.message);
      }
    });
  }

  // Debug form errors on change
  React.useEffect(() => {
    const subscription = form.watch(() => {
      console.log("Form values changed:", form.getValues());
      console.log("Form errors:", form.formState.errors);
    });
    return () => subscription.unsubscribe();
  }, [form]);

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="flex flex-col h-full sm:max-w-xl bg-gray-50">
        <SheetHeader className="text-left flex-shrink-0">
          <SheetTitle className="text-2xl font-bold">RFQ 미리보기</SheetTitle>
          <SheetDescription className="">
            RFQ 정보를 확인하고 필요한 항목을 수정하세요. RFQ Title, Context, 마감일만 수정 가능합니다.
          </SheetDescription>
        </SheetHeader>

        <div className="flex-1 overflow-y-auto py-4">
          {isLoading ? (
            <div className="flex justify-center items-center py-12">
              <Loader2 className="h-10 w-10 animate-spin" />
            </div>
          ) : (
            <div className="space-y-6">
              {/* 프로젝트 정보 */}
              <div className="bg-white shadow-sm rounded-lg p-5 border border-gray-200">
                <h3 className="text-lg font-semibold mb-3 text-gray-800">프로젝트 정보</h3>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="font-semibold text-gray-700">프로젝트명:</span> {projectInfo.projNm}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">섹터:</span> {projectInfo.sector}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">척수:</span> {projectInfo.projMsrm}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">선종:</span> {projectInfo.ptypeNm}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">RFQ No:</span> {projectInfo.rfqNo}
                  </div>
                </div>
              </div>

              {/* 시리즈 정보 - 프로젝트 정보 아래에 배치 */}
              <div className="bg-white shadow-sm rounded-lg p-5 border border-gray-200">
                <h3 className="text-lg font-semibold mb-3 text-gray-800">시리즈 정보</h3>
                {isLoadingSeries ? (
                  <div className="text-center py-4 text-gray-500">
                    시리즈 정보 로딩 중...
                  </div>
                ) : seriesInfo && seriesInfo.length > 0 ? (
                  <div className="grid grid-cols-1 gap-3">
                    {seriesInfo.map((series) => (
                      <div key={series.sersNo} className="bg-gray-50 rounded border p-3">
                        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 text-sm">
                          <div>
                            <span className="font-medium text-gray-700">시리즈번호:</span>
                            <div className="text-gray-900">{series.sersNo}</div>
                          </div>
                          <div>
                            <span className="font-medium text-gray-700">K/L (Keel Laying):</span>
                            <div className="text-gray-900">{convertKLToQuarter(series.klDt)}</div>
                          </div>
                          <div>
                            <span className="font-medium text-gray-700">도크코드:</span>
                            <div className="text-gray-900">{series.dockNo || "N/A"}</div>
                          </div>
                          <div>
                            <span className="font-medium text-gray-700">도크명:</span>
                            <div className="text-gray-900">{series.dockNm || "N/A"}</div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-4 text-gray-500">
                    시리즈 데이터가 없습니다.
                  </div>
                )}
              </div>

              {/* RFQ 정보 */}
              {/* <div className="bg-white shadow-sm rounded-lg p-5 border border-gray-200">
                <h3 className="text-lg font-semibold mb-3 text-gray-800">RFQ 정보</h3>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="font-semibold text-gray-700">상태:</span> {rfqInfo.status}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">생성자:</span> {rfqInfo.createdByName}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">생성일:</span> {rfqInfo.createdAt}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">수정자:</span> {rfqInfo.updatedByName}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">수정일:</span> {rfqInfo.updatedAt}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">발송자:</span> {rfqInfo.sentByName}
                  </div>
                  <div>
                    <span className="font-semibold text-gray-700">발송일:</span> {rfqInfo.rfqSendDate}
                  </div>
                </div>
              </div> */}

              <Form {...form}>
                <form id="update-rfq-form" onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">
                  <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-sm font-medium text-gray-700">RFQ Title</FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            placeholder="RFQ Title을 입력하세요"
                            className="border-gray-300 rounded-md"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="remark"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-sm font-medium text-gray-700">RFQ Context</FormLabel>
                        <FormControl>
                          <Textarea
                            {...field}
                            placeholder="RFQ Context를 입력하세요"
                            className="border-gray-300 rounded-md min-h-[100px]"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="dueDate"
                    render={({ field }) => (
                      <FormItem className="flex flex-col">
                        <FormLabel>마감일</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(new Date(field.value), "PPP", { locale: ko })
                                ) : (
                                  <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 ? new Date(field.value) : undefined}
                              onSelect={(date) => {
                                // date-fns format을 사용해 yyyy-MM-dd로 변환하여 string 저장
                                if (date) {
                                  field.onChange(format(date, "yyyy-MM-dd"));
                                }
                              }}
                              disabled={(date) =>
                                date < new Date() || date < new Date("1900-01-01")
                              }
                              initialFocus
                            />
                          </PopoverContent>
                        </Popover>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </form>
              </Form>
            </div>
          )}
        </div>

        <SheetFooter className="gap-2 pt-2 sm:space-x-0 flex-shrink-0">
          <SheetClose asChild>
            <Button
              type="button"
              variant="outline"
              disabled={isPending}
              className="border-gray-300 text-gray-700 hover:bg-gray-100 rounded-md"
            >
              취소
            </Button>
          </SheetClose>
          <Button
            type="submit"
            form="update-rfq-form"
            disabled={isPending}
            className="bg-blue-600 hover:bg-blue-700 text-white rounded-md"
            onClick={() => console.log("Save button clicked")}
          >
            {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
            저장
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}