"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 { 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";

// Zod schema for form validation
const updateRfqSchema = z.object({
  rfqId: z.number().min(1, "RFQ ID is required"),
  description: 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: "",
  });
  const [isLoading, setIsLoading] = React.useState(false);

  // Initialize form with React Hook Form and Zod
  const form = useForm<UpdateRfqSchema>({
    resolver: zodResolver(updateRfqSchema),
    defaultValues: {
      rfqId,
      description: "",
      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 || "",
          dueDate: result.data.dueDate ? new Date(result.data.dueDate).toISOString().slice(0, 10) : "",
        });
        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 || "",
        });
      }
    } 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,
          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 정보를 수정합니다. 모든 필드를 입력한 후 저장 버튼을 클릭하세요.
          </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">
                <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>

              <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="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>
  );
}