"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { toast } from "sonner"

import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"

import { useSession } from "next-auth/react"
import { createRfqSchema, type CreateRfqSchema } from "../validations"
import { createRfq, generateNextRfqCode } from "../service"
import { type Project } from "../service"
import { EstimateProjectSelector } from "@/components/BidProjectSelector"




export function AddRfqDialog() {
  const [open, setOpen] = React.useState(false)
  const { data: session, status } = useSession()
  const [isLoadingRfqCode, setIsLoadingRfqCode] = React.useState(false)


  // Get the user ID safely, ensuring it's a valid number
  const userId = React.useMemo(() => {
    const id = session?.user?.id ? Number(session.user.id) : null;

    return id;
  }, [session, status]);



  // RHF + Zod
  const form = useForm<CreateRfqSchema>({
    resolver: zodResolver(createRfqSchema),
    defaultValues: {
      rfqCode: "",
      description: "",
      projectId: undefined,
      dueDate: new Date(),
      status: "DRAFT",
      // Don't set createdBy yet - we'll set it when the form is submitted
      createdBy: undefined,
    },
  });

  // Update form values when session loads
  React.useEffect(() => {
    if (status === "authenticated" && userId) {
      form.setValue("createdBy", userId);
    }
  }, [status, userId, form]);

  // 다이얼로그가 열릴 때 자동으로 RFQ 코드 생성
  React.useEffect(() => {
    if (open) {
      const generateRfqCode = async () => {
        setIsLoadingRfqCode(true);
        try {
          // 서버 액션 호출
          const result = await generateNextRfqCode();

          if (result.error) {
            toast.error(`RFQ 코드 생성 실패: ${result.error}`);
            return;
          }

          // 생성된 코드를 폼에 설정
          form.setValue("rfqCode", result.code);
        } catch (error) {
          console.error("RFQ 코드 생성 오류:", error);
          toast.error("RFQ 코드 생성에 실패했습니다");
        } finally {
          setIsLoadingRfqCode(false);
        }
      };

      generateRfqCode();
    }
  }, [open, form]);





  const handleBidProjectSelect = (project: Project | null) => {
    if (project === null) {
      return;
    }

    form.setValue("bidProjectId", project.id);
  };


  async function onSubmit(data: CreateRfqSchema) {
    // Check if user is authenticated before submitting
    if (status !== "authenticated" || !userId) {
      toast.error("사용자 인증이 필요합니다. 다시 로그인해주세요.");
      return;
    }

    // Make sure createdBy is set with the current user ID
    const submitData = {
      ...data,
      createdBy: userId
    };

    const result = await createRfq(submitData);
    if (result.error) {
      toast.error(`에러: ${result.error}`);
      return;
    }

    toast.success("RFQ가 성공적으로 생성되었습니다.");
    form.reset();

    setOpen(false);
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    if (!nextOpen) {
      form.reset();
    }
    setOpen(nextOpen);
  }

  // Return a message or disabled state if user is not authenticated
  if (status === "loading") {
    return <Button variant="outline" size="sm" disabled>Loading...</Button>;
  }


  return (
    <Dialog open={open} onOpenChange={handleDialogOpenChange}>
      {/* 모달을 열기 위한 버튼 */}
      <DialogTrigger asChild>
        <Button variant="default" size="sm">
          Add RFQ
        </Button>
      </DialogTrigger>

      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create New RFQ</DialogTitle>
          <DialogDescription>
            새 RFQ 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="space-y-4 py-4">

              {/* Project Selector */}
              <FormField
                control={form.control}
                name="projectId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Project</FormLabel>
                    <FormControl>
                        <EstimateProjectSelector
                          selectedProjectId={field.value}
                          onProjectSelect={handleBidProjectSelect}
                          placeholder="견적 프로젝트 선택..."
                        />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* rfqCode - 자동 생성되고 읽기 전용 */}
              <FormField
                control={form.control}
                name="rfqCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>RFQ Code</FormLabel>
                    <FormControl>
                      <div className="flex">
                        <Input
                          placeholder="자동으로 생성 중..."
                          {...field}
                          disabled={true}
                          className="bg-muted"
                        />
                        {isLoadingRfqCode && (
                          <div className="ml-2 flex items-center">
                            <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                          </div>
                        )}
                      </div>
                    </FormControl>
                    <div className="text-xs text-muted-foreground mt-1">
                      RFQ 타입과 현재 날짜를 기준으로 자동 생성됩니다
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* description */}
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>RFQ Description</FormLabel>
                    <FormControl>
                      <Input placeholder="e.g. 설명을 입력하세요" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* dueDate */}
              <FormField
                control={form.control}
                name="dueDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Due Date</FormLabel>
                    <FormControl>
                      <Input
                        type="date"
                        value={field.value ? field.value.toISOString().slice(0, 10) : ""}
                        onChange={(e) => {
                          const val = e.target.value
                          if (val) {
                            const date = new Date(val);
                            // 날짜 1일씩 밀리는 문제로 우선 KTC로 입력
                            // 추후 아래와 같이 수정
                            // 1. 해당 유저 타임존 값으로 입력
                            // 2. DB에는 UTC 타임존 값으로 저장
                            // 3. 출력시 유저별 타임존 값으로 변환해 출력
                            // 4. 어떤 타임존으로 나오는지도 함께 렌더링
                            // field.onChange(new Date(val + "T00:00:00"))
                            field.onChange(date);
                          }
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* status (Read-only) */}
              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Status</FormLabel>
                    <FormControl>
                      <Input
                        disabled
                        className="capitalize"
                        {...field}
                        onChange={() => { }} // Prevent changes
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setOpen(false)}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={form.formState.isSubmitting || status !== "authenticated"}
              >
                Create
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}