"use client";

import * as React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
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 { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Plus, Trash2 } from "lucide-react";
import { createComplianceQuestion, createComplianceQuestionOption, getComplianceQuestionsCount, getComplianceQuestions, getComplianceQuestionOptions } from "@/lib/compliance/services";
import { QUESTION_TYPES } from "@/db/schema/compliance";
import { toast } from "sonner";
import { useRouter } from "next/navigation";

const questionSchema = z.object({
  questionNumber: z.string().min(1, "질문 번호를 입력하세요"),
  questionText: z.string().min(1, "질문 내용을 입력하세요"),
  questionType: z.string().min(1, "질문 유형을 선택하세요"),
  isRequired: z.boolean(),
  hasDetailText: z.boolean(),
  hasFileUpload: z.boolean(),
  conditionalValue: z.string().optional(),
});

type QuestionFormData = z.infer<typeof questionSchema>;

interface ComplianceQuestionCreateDialogProps {
  templateId: number;
  onSuccess?: () => void;
}

export function ComplianceQuestionCreateDialog({ 
  templateId, 
  onSuccess 
}: ComplianceQuestionCreateDialogProps) {
  const [open, setOpen] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);
  const router = useRouter();

  const form = useForm<QuestionFormData>({
    resolver: zodResolver(questionSchema),
    defaultValues: {
      questionNumber: "",
      questionText: "",
      questionType: "",
      isRequired: false,
      hasDetailText: false,
      hasFileUpload: false,
      conditionalValue: "",
    },
  });

  // 부모 질문 및 옵션 상태
  const [parentQuestionId, setParentQuestionId] = React.useState<number | "">("");
  const [selectableParents, setSelectableParents] = React.useState<Array<{ id: number; questionNumber: string; questionText: string; questionType: string }>>([]);
  const [parentOptions, setParentOptions] = React.useState<Array<{ id: number; optionValue: string; optionText: string }>>([]);
  
  // 옵션 관리 상태
  const [options, setOptions] = React.useState<Array<{ optionValue: string; optionText: string; allowsOtherInput: boolean; displayOrder: number }>>([]);
  const [newOptionValue, setNewOptionValue] = React.useState("");
  const [newOptionText, setNewOptionText] = React.useState("");
  const [newOptionOther, setNewOptionOther] = React.useState(false);
  const [showOptionForm, setShowOptionForm] = React.useState(false);

  // 선택형 질문인지 확인
  const isSelectionType = React.useMemo(() => {
    const questionType = form.watch("questionType");
    return [QUESTION_TYPES.RADIO, QUESTION_TYPES.CHECKBOX, QUESTION_TYPES.DROPDOWN].includes((questionType || "").toUpperCase() as any);
  }, [form.watch("questionType")]);

  // 시트/다이얼로그 열릴 때 부모 후보 로드 (같은 템플릿 내 선택형 질문만)
  React.useEffect(() => {
    if (!open) return;
    (async () => {
      try {
        const qs = await getComplianceQuestions(templateId);
        const filtered = (qs || []).filter((q: any) => [QUESTION_TYPES.RADIO, QUESTION_TYPES.CHECKBOX, QUESTION_TYPES.DROPDOWN].includes((q.questionType || "").toUpperCase()));
        setSelectableParents(filtered);
      } catch (e) {
        console.error("load selectable parents error", e);
      }
    })();
  }, [open, templateId]);

  // 부모 선택 시 옵션 로드
  React.useEffect(() => {
    if (!open) return;
    (async () => {
      if (!parentQuestionId) { setParentOptions([]); return; }
      try {
        const opts = await getComplianceQuestionOptions(Number(parentQuestionId));
        setParentOptions(opts.map((o: any) => ({ id: o.id, optionValue: o.optionValue, optionText: o.optionText })));
      } catch (e) {
        console.error("load parent options error", e);
        setParentOptions([]);
      }
    })();
  }, [open, parentQuestionId]);

  const onSubmit = async (data: QuestionFormData) => {
    try {
      setIsLoading(true);
      
      // 새로운 질문의 displayOrder는 기존 질문 개수 + 1
      const currentQuestionsCount = await getComplianceQuestionsCount(templateId);
      
      const newQuestion = await createComplianceQuestion({
        templateId,
        ...data,
        parentQuestionId: data.isConditional && parentQuestionId ? Number(parentQuestionId) : null,
        displayOrder: currentQuestionsCount + 1,
      });

      // 선택형 질문이고 옵션이 있다면 옵션들도 생성
      if (isSelectionType && options.length > 0 && newQuestion) {
        try {
          // 옵션들을 순차적으로 생성
          for (let i = 0; i < options.length; i++) {
            const option = options[i];
            await createComplianceQuestionOption({
              questionId: newQuestion.id,
              optionValue: option.optionValue,
              optionText: option.optionText,
              allowsOtherInput: option.allowsOtherInput,
              displayOrder: i + 1,
            });
          }
        } catch (optionError) {
          console.error("Error creating options:", optionError);
          toast.error("질문은 생성되었지만 옵션 생성 중 오류가 발생했습니다.");
        }
      }

      toast.success("질문이 성공적으로 추가되었습니다.");
      setOpen(false);
      form.reset();
      setOptions([]);
      setShowOptionForm(false);
      
      // 페이지 새로고침
      router.refresh();
      
      if (onSuccess) {
        onSuccess();
      }
    } catch (error) {
      console.error("Error creating question:", error);
      
      // 중복 질문번호 오류 처리
      if (error instanceof Error && error.message === "DUPLICATE_QUESTION_NUMBER") {
        form.setError("questionNumber", {
          type: "manual",
          message: "이미 사용 중인 질문번호입니다."
        });
        toast.error("이미 사용 중인 질문번호입니다.");
      } else {
        toast.error("질문 추가 중 오류가 발생했습니다.");
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          <Plus className="mr-2 h-4 w-4" />
          질문 추가
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>새 질문 추가</DialogTitle>
          <DialogDescription>
            템플릿에 새로운 질문을 추가합니다.
          </DialogDescription>
        </DialogHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="questionNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>질문 번호</FormLabel>
                  <FormControl>
                    <Input placeholder="Q1" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="questionText"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>질문 내용</FormLabel>
                  <FormControl>
                    <Textarea 
                      placeholder="질문 내용을 입력하세요" 
                      className="min-h-[100px]"
                      {...field} 
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="questionType"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>질문 유형</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="질문 유형을 선택하세요" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {Object.entries(QUESTION_TYPES).map(([key, value]) => (
                        <SelectItem key={key} value={value}>
                          {value}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 옵션 관리 (선택형 질문일 때만) */}
            {isSelectionType && (
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <div className="text-sm font-medium">옵션 관리</div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      setNewOptionValue("");
                      setNewOptionText("");
                      setNewOptionOther(false);
                      setShowOptionForm(true);
                    }}
                  >
                    <Plus className="h-4 w-4 mr-1" />
                    옵션 추가
                  </Button>
                </div>

                {/* 옵션 추가 폼 */}
                {showOptionForm && (
                  <div className="space-y-3 p-3 border rounded-lg bg-muted/50">
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <Input 
                          value={newOptionValue} 
                          onChange={(e) => setNewOptionValue(e.target.value)} 
                          placeholder="option_value (예: YES)" 
                        />
                      </div>
                      <div>
                        <Input 
                          value={newOptionText} 
                          onChange={(e) => setNewOptionText(e.target.value)} 
                          placeholder="option_text (표시 라벨)" 
                        />
                      </div>
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Checkbox 
                          checked={newOptionOther} 
                          onCheckedChange={(v) => setNewOptionOther(Boolean(v))} 
                        />
                        <span className="text-sm text-muted-foreground">기타 허용</span>
                      </div>
                      <div className="flex gap-2">
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            if (!newOptionValue || !newOptionText) {
                              toast.error("option_value와 option_text를 입력하세요.");
                              return;
                            }
                            const newOption = {
                              optionValue: newOptionValue.toUpperCase(),
                              optionText: newOptionText,
                              allowsOtherInput: newOptionOther,
                              displayOrder: options.length + 1,
                            };
                            setOptions([...options, newOption]);
                            setNewOptionValue("");
                            setNewOptionText("");
                            setNewOptionOther(false);
                            setShowOptionForm(false);
                            toast.success("옵션이 추가되었습니다.");
                          }}
                        >
                          등록
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setShowOptionForm(false);
                            setNewOptionValue("");
                            setNewOptionText("");
                            setNewOptionOther(false);
                          }}
                        >
                          취소
                        </Button>
                      </div>
                    </div>
                  </div>
                )}

                {/* 등록된 옵션 목록 */}
                <div className="space-y-2">
                  {options.length === 0 ? (
                    <div className="text-xs text-muted-foreground">등록된 옵션이 없습니다.</div>
                  ) : (
                    options.map((opt, index) => (
                      <div key={index} className="flex items-center gap-3 rounded border p-2">
                        <div className="text-xs text-muted-foreground w-10">#{opt.displayOrder}</div>
                        <div className="text-sm font-mono">{opt.optionValue}</div>
                        <div className="text-sm flex-1">{opt.optionText}</div>
                        {opt.allowsOtherInput && <Badge variant="secondary">기타 허용</Badge>}
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          onClick={() => {
                            const newOptions = options.filter((_, i) => i !== index);
                            setOptions(newOptions);
                            toast.success("옵션이 제거되었습니다.");
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    ))
                  )}
                </div>
              </div>
            )}

            {/* 조건부 질문 체크박스 */}


            <div className="grid grid-cols-3 gap-4">
              <FormField
                control={form.control}
                name="isRequired"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>필수 질문</FormLabel>
                      <FormDescription>
                        응답자가 반드시 답변해야 하는 질문
                      </FormDescription>
                    </div>
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="hasDetailText"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>상세 설명</FormLabel>
                      <FormDescription>
                        추가 설명 입력 가능
                      </FormDescription>
                    </div>
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="hasFileUpload"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>파일 업로드</FormLabel>
                      <FormDescription>
                        파일 첨부 가능
                      </FormDescription>
                    </div>
                  </FormItem>
                )}
              />
            </div>

            {/* 조건부 질문 체크박스 */}
            <FormField
              control={form.control}
              name="isConditional"
              render={({ field }) => (
                <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                  <FormControl>
                    <Checkbox
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                  <div className="space-y-1 leading-none">
                    <FormLabel>조건부 질문</FormLabel>
                    <FormDescription>
                      특정 조건에 따라 표시되는 질문
                    </FormDescription>
                  </div>
                </FormItem>
              )}
            />

            {/* 조건부 질문일 때만 부모 질문과 조건값 표시 */}
            {form.watch("isConditional") && (
              <div className="space-y-2">
                {/* 조건 질문 선택 */}
                <div>
                  <FormLabel>조건 질문</FormLabel>
                  <Select onValueChange={(v) => setParentQuestionId(v as any)} value={(parentQuestionId as any) || ""}>
                    <SelectTrigger>
                      <SelectValue placeholder="조건 기준 질문을 선택하세요">
                        {parentQuestionId ? (
                          <div className="truncate max-w-[300px] text-left">
                            {selectableParents.find(p => String(p.id) === parentQuestionId)?.questionText}
                          </div>
                        ) : null}
                      </SelectValue>
                    </SelectTrigger>
                    <SelectContent>
                      {selectableParents.map((p) => (
                        <SelectItem key={p.id} value={String(p.id)}>
                          {p.questionText}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* 조건값 선택 */}
                <FormField
                  control={form.control}
                  name="conditionalValue"
                  render={({ field }) => (
                    <FormItem className="space-y-1">
                      <FormLabel>조건값</FormLabel>
                      {parentOptions.length > 0 ? (
                        <>
                          <Select onValueChange={field.onChange} defaultValue={(field.value || "").toString()}>
                            <SelectTrigger>
                              <SelectValue placeholder="조건값을 선택하세요" />
                            </SelectTrigger>
                            <SelectContent>
                              {parentOptions.map((opt) => (
                                <SelectItem key={opt.id} value={opt.optionValue}>
                                  {opt.optionValue}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </>
                      ) : (
                        <>
                          <FormControl>
                            <Input placeholder="먼저 부모 질문을 선택하세요" disabled />
                          </FormControl>
                          <FormDescription>조건 질문을 선택하세요.</FormDescription>
                        </>
                      )}
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            )}

            {/* 기존 조건값 입력 필드는 부모/조건값 섹션으로 대체됨 */}

            <DialogFooter>
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => setOpen(false)}
                disabled={isLoading}
              >
                취소
              </Button>
              <Button type="submit" disabled={isLoading}>
                {isLoading ? "추가 중..." : "질문 추가"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
