"use client"

import { useEffect, useTransition, useState, useRef } from "react"
import { useRouter, useParams } from "next/navigation"
import { z } from "zod"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Search, X } from "lucide-react"
import { customAlphabet } from "nanoid"

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { cn } from "@/lib/utils"
import { EVALUATION_TARGET_FILTER_OPTIONS } from "../validation"

// nanoid 생성기
const generateId = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 6)

// 평가 대상 필터 스키마 정의
const evaluationTargetFilterSchema = z.object({
  evaluationYear: z.string().optional(),
  division: z.string().optional(),
  status: z.string().optional(),
  domesticForeign: z.string().optional(),
  materialType: z.string().optional(),
  consensusStatus: z.string().optional(),
  vendorCode: z.string().optional(),
  vendorName: z.string().optional(),
  reviewerUserId: z.string().optional(),
  orderReviewerName: z.string().optional(),
  procurementReviewerName: z.string().optional(),
  qualityReviewerName: z.string().optional(),
  designReviewerName: z.string().optional(),
  csReviewerName: z.string().optional(),
})


type EvaluationTargetFilterFormValues = z.infer<typeof evaluationTargetFilterSchema>

interface EvaluationTargetFilterSheetProps {
  isOpen: boolean;
  onClose: () => void;
  onFiltersApply: (filters: any[], joinOperator: "and" | "or") => void; // ✅ 필터 전달 콜백
  isLoading?: boolean;
}

export function EvaluationTargetFilterSheet({
  isOpen,
  onClose,
  onFiltersApply,
  isLoading = false
}: EvaluationTargetFilterSheetProps) {
  const router = useRouter()
  const params = useParams();
  const lng = params ? (params.lng as string) : 'ko';

  const [isPending, startTransition] = useTransition()
  const [joinOperator, setJoinOperator] = useState<"and" | "or">("and")

  // 폼 상태 초기화
  const form = useForm<EvaluationTargetFilterFormValues>({
    resolver: zodResolver(evaluationTargetFilterSchema),
    defaultValues: {
      evaluationYear: new Date().getFullYear().toString(),
      division: "",
      status: "",
      domesticForeign: "",
      materialType: "",
      consensusStatus: "",
      vendorCode: "",
      vendorName: "",
      reviewerUserId: "",
      orderReviewerName: "",
      procurementReviewerName: "",
      qualityReviewerName: "",
      designReviewerName: "",
      csReviewerName: "",
    },
  })

  // ✅ 폼 제출 핸들러 - 필터 배열 생성 및 전달
  async function onSubmit(data: EvaluationTargetFilterFormValues) {
    startTransition(async () => {
      try {
        const newFilters = []

        // 필터 생성 로직
        if (data.evaluationYear?.trim()) {
          newFilters.push({
            id: "evaluationYear",
            value: parseInt(data.evaluationYear.trim()),
            type: "number",
            operator: "eq",
            rowId: generateId()
          })
        }

        if (data.division?.trim()) {
          newFilters.push({
            id: "division",
            value: data.division.trim(),
            type: "select",
            operator: "eq",
            rowId: generateId()
          })
        }

        if (data.status?.trim()) {
          newFilters.push({
            id: "status",
            value: data.status.trim(),
            type: "select",
            operator: "eq",
            rowId: generateId()
          })
        }

        if (data.domesticForeign?.trim()) {
          newFilters.push({
            id: "domesticForeign",
            value: data.domesticForeign.trim(),
            type: "select",
            operator: "eq",
            rowId: generateId()
          })
        }

        if (data.materialType?.trim()) {
          newFilters.push({
            id: "materialType",
            value: data.materialType.trim(),
            type: "select",
            operator: "eq",
            rowId: generateId()
          })
        }

        if (data.consensusStatus?.trim()) {
          newFilters.push({
            id: "consensusStatus",
            value: data.consensusStatus.trim(),
            type: "select",
            operator: "eq",
            rowId: generateId()
          })
        }

        if (data.vendorCode?.trim()) {
          newFilters.push({
            id: "vendorCode",
            value: data.vendorCode.trim(),
            type: "text",
            operator: "iLike",
            rowId: generateId()
          })
        }

        if (data.vendorName?.trim()) {
          newFilters.push({
            id: "vendorName",
            value: data.vendorName.trim(),
            type: "text",
            operator: "iLike",
            rowId: generateId()
          })
        }

        if (data.reviewerUserId?.trim()) {
          newFilters.push({
            id: "reviewerUserId",
            value: parseInt(data.reviewerUserId.trim()),
            type: "number",
            operator: "eq",
            rowId: generateId()
          })
        }

        if (data.orderReviewerName?.trim()) {
          newFilters.push({
            id: "orderReviewerName",
            value: data.orderReviewerName.trim(),
            type: "text",
            operator: "iLike",
            rowId: generateId()
          })
        }

        if (data.procurementReviewerName?.trim()) {
          newFilters.push({
            id: "procurementReviewerName",
            value: data.procurementReviewerName.trim(),
            type: "text",
            operator: "iLike",
            rowId: generateId()
          })
        }

        if (data.qualityReviewerName?.trim()) {
          newFilters.push({
            id: "qualityReviewerName",
            value: data.qualityReviewerName.trim(),
            type: "text",
            operator: "iLike",
            rowId: generateId()
          })
        }

        if (data.designReviewerName?.trim()) {
          newFilters.push({
            id: "designReviewerName",
            value: data.designReviewerName.trim(),
            type: "text",
            operator: "iLike",
            rowId: generateId()
          })
        }

        if (data.csReviewerName?.trim()) {
          newFilters.push({
            id: "csReviewerName",
            value: data.csReviewerName.trim(),
            type: "text",
            operator: "iLike",
            rowId: generateId()
          })
        }

        console.log("=== 생성된 필터들 ===", newFilters);
        console.log("=== 조인 연산자 ===", joinOperator);

        // ✅ 부모 컴포넌트에 필터 전달
        onFiltersApply(newFilters, joinOperator);

        console.log("=== 필터 적용 완료 ===");
      } catch (error) {
        console.error("평가 대상 필터 적용 오류:", error);
      }
    })
  }

  // ✅ 필터 초기화 핸들러
  function handleReset() {
    // 1. 폼 초기화
    form.reset({
      evaluationYear: "",
      division: "",
      status: "",
      domesticForeign: "",
      materialType: "",
      consensusStatus: "",
      vendorCode: "",
      vendorName: "",
      reviewerUserId: "",
      orderReviewerName: "",
      procurementReviewerName: "",
      qualityReviewerName: "",
      designReviewerName: "",
      csReviewerName: "",
    });

    // 2. 조인 연산자 초기화
    setJoinOperator("and");

    // 3. URL 파라미터 초기화 (필터를 빈 배열로 설정)
    const currentUrl = new URL(window.location.href);
    const newSearchParams = new URLSearchParams(currentUrl.search);
    
    // 필터 관련 파라미터 초기화
    newSearchParams.set("filters", JSON.stringify([]));
    newSearchParams.set("joinOperator", "and");
    newSearchParams.set("page", "1");
    newSearchParams.delete("search"); // 검색어 제거
    
    // URL 업데이트
    router.replace(`${currentUrl.pathname}?${newSearchParams.toString()}`);

    // 4. 빈 필터 배열 전달 (즉시 UI 업데이트를 위해)
    onFiltersApply([], "and");

    console.log("=== 필터 완전 초기화 완료 ===");
  }

  if (!isOpen) {
    return null;
  }

  return (
    <div className="flex flex-col h-full max-h-full bg-[#F5F7FB] px-6 sm:px-8" style={{backgroundColor:"#F5F7FB", paddingLeft:"2rem", paddingRight:"2rem"}}>
      {/* Filter Panel Header */}
      <div className="flex items-center justify-between px-6 min-h-[60px] shrink-0">
        <h3 className="text-lg font-semibold whitespace-nowrap">평가 대상 검색 필터</h3>
        <Button
          variant="ghost"
          size="icon"
          onClick={onClose}
          className="h-8 w-8"
        >
          <X className="size-4" />
        </Button>
      </div>

      {/* Join Operator Selection */}
      <div className="px-6 shrink-0">
        <label className="text-sm font-medium">조건 결합 방식</label>
        <Select
          value={joinOperator}
          onValueChange={(value: "and" | "or") => setJoinOperator(value)}
        >
          <SelectTrigger className="h-8 w-[180px] mt-2 bg-white">
            <SelectValue placeholder="조건 결합 방식" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="and">모든 조건 충족 (AND)</SelectItem>
            <SelectItem value="or">하나라도 충족 (OR)</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col h-full min-h-0">
          {/* Scrollable content area */}
          <div className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">
            <div className="space-y-4 pt-2">
              
              {/* 평가년도 */}
              <FormField
                control={form.control}
                name="evaluationYear"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>평가년도</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          type="number"
                          placeholder="평가년도 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("evaluationYear", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 구분 */}
              <FormField
                control={form.control}
                name="division"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>구분</FormLabel>
                    <Select
                      value={field.value}
                      onValueChange={field.onChange}
                    >
                      <FormControl>
                        <SelectTrigger className={cn(field.value && "pr-8", "bg-white")}>
                          <div className="flex justify-between w-full">
                            <SelectValue placeholder="구분 선택" />
                            {field.value && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 -mr-2"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  form.setValue("division", "");
                                }}
                              >
                                <X className="size-3" />
                              </Button>
                            )}
                          </div>
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {EVALUATION_TARGET_FILTER_OPTIONS.DIVISIONS.map(option => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 상태 */}
              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>상태</FormLabel>
                    <Select
                      value={field.value}
                      onValueChange={field.onChange}
                    >
                      <FormControl>
                        <SelectTrigger className={cn(field.value && "pr-8", "bg-white")}>
                          <div className="flex justify-between w-full">
                            <SelectValue placeholder="상태 선택" />
                            {field.value && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 -mr-2"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  form.setValue("status", "");
                                }}
                              >
                                <X className="size-3" />
                              </Button>
                            )}
                          </div>
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {EVALUATION_TARGET_FILTER_OPTIONS.STATUSES.map(option => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 내외자 구분 */}
              <FormField
                control={form.control}
                name="domesticForeign"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>내외자 구분</FormLabel>
                    <Select
                      value={field.value}
                      onValueChange={field.onChange}
                    >
                      <FormControl>
                        <SelectTrigger className={cn(field.value && "pr-8", "bg-white")}>
                          <div className="flex justify-between w-full">
                            <SelectValue placeholder="내외자 구분 선택" />
                            {field.value && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 -mr-2"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  form.setValue("domesticForeign", "");
                                }}
                              >
                                <X className="size-3" />
                              </Button>
                            )}
                          </div>
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {EVALUATION_TARGET_FILTER_OPTIONS.DOMESTIC_FOREIGN.map(option => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 자재구분 */}
              <FormField
                control={form.control}
                name="materialType"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>자재구분</FormLabel>
                    <Select
                      value={field.value}
                      onValueChange={field.onChange}
                    >
                      <FormControl>
                        <SelectTrigger className={cn(field.value && "pr-8", "bg-white")}>
                          <div className="flex justify-between w-full">
                            <SelectValue placeholder="자재구분 선택" />
                            {field.value && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 -mr-2"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  form.setValue("materialType", "");
                                }}
                              >
                                <X className="size-3" />
                              </Button>
                            )}
                          </div>
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {EVALUATION_TARGET_FILTER_OPTIONS.MATERIAL_TYPES.map(option => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 의견 일치 여부 */}
              <FormField
                control={form.control}
                name="consensusStatus"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>의견 일치 여부</FormLabel>
                    <Select
                      value={field.value}
                      onValueChange={field.onChange}
                    >
                      <FormControl>
                        <SelectTrigger className={cn(field.value && "pr-8", "bg-white")}>
                          <div className="flex justify-between w-full">
                            <SelectValue placeholder="의견 일치 여부 선택" />
                            {field.value && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="h-4 w-4 -mr-2"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  form.setValue("consensusStatus", "");
                                }}
                              >
                                <X className="size-3" />
                              </Button>
                            )}
                          </div>
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {EVALUATION_TARGET_FILTER_OPTIONS.CONSENSUS_STATUS.map(option => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 벤더 코드 */}
              <FormField
                control={form.control}
                name="vendorCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>벤더 코드</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="벤더 코드 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("vendorCode", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 벤더명 */}
              <FormField
                control={form.control}
                name="vendorName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>벤더명</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="벤더명 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("vendorName", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 담당자 ID */}
              <FormField
                control={form.control}
                name="reviewerUserId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>담당자 ID</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          type="number"
                          placeholder="담당자 ID 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("reviewerUserId", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 발주 담당자명 */}
              <FormField
                control={form.control}
                name="orderReviewerName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>발주 담당자명</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="발주 담당자명 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("orderReviewerName", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 조달 담당자명 */}
              <FormField
                control={form.control}
                name="procurementReviewerName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>조달 담당자명</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="조달 담당자명 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("procurementReviewerName", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 품질 담당자명 */}
              <FormField
                control={form.control}
                name="qualityReviewerName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>품질 담당자명</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="품질 담당자명 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("qualityReviewerName", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 설계 담당자명 */}
              <FormField
                control={form.control}
                name="designReviewerName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>설계 담당자명</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="설계 담당자명 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("designReviewerName", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* CS 담당자명 */}
              <FormField
                control={form.control}
                name="csReviewerName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>CS 담당자명</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="CS 담당자명 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            className="absolute right-0 top-0 h-full px-2"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("csReviewerName", "");
                            }}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

            </div>
          </div>

          {/* Fixed buttons at bottom */}
          <div className="p-4 shrink-0">
            <div className="flex gap-2 justify-end">
              <Button
                type="button"
                variant="outline"
                onClick={handleReset}
                disabled={isPending}
                className="px-4"
              >
                초기화
              </Button>
              <Button
                type="submit"
                variant="samsung"
                disabled={isPending || isLoading}
                className="px-4"
              >
                <Search className="size-4 mr-2" />
                {isPending || isLoading ? "조회 중..." : "조회"}
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </div>
  )
}