"use client";

import { useEffect, useTransition, useState, useRef } from "react";
import { useRouter } 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 { parseAsStringEnum, useQueryState } from "nuqs";

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 { getFiltersStateParser } from "@/lib/parsers";
import { EVALUATION_TARGET_FILTER_OPTIONS } from "@/lib/evaluation-target-list/validation";

/*****************************************************************************************
 * UTILS & CONSTANTS
 *****************************************************************************************/

// nanoid generator (6‑chars [0-9a-zA-Z])
const generateId = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 6);

// ── SELECT OPTIONS ──────────────────────────────────────────────────────────────────────

const statusOptions = [
  { value: "PENDING", label: "대상확정" },
  { value: "PENDING_SUBMISSION", label: "자료접수중" },
  { value: "SUBMITTED", label: "제출완료" },
  { value: "IN_REVIEW", label: "평가중" },
  { value: "REVIEW_COMPLETED", label: "평가완료" },
  { value: "FINALIZED", label: "결과확정" },
];


const documentsSubmittedOptions = [
  { value: "true", label: "제출완료" },
  { value: "false", label: "미제출" },
];

const gradeOptions = [
  { value: "A", label: "A등급" },
  { value: "B", label: "B등급" },
  { value: "C", label: "C등급" },
  { value: "D", label: "D등급" },
];

/*****************************************************************************************
 * ZOD SCHEMA & TYPES
 *****************************************************************************************/
const periodicEvaluationFilterSchema = z.object({
  evaluationYear: z.string().optional(),
  division: z.string().optional(),
  status: z.string().optional(),
  domesticForeign: z.string().optional(),
  materialType: z.string().optional(),
  vendorCode: z.string().optional(),
  vendorName: z.string().optional(),
  documentsSubmitted: z.string().optional(),
  evaluationGrade: z.string().optional(),
  finalGrade: z.string().optional(),
  minTotalScore: z.string().optional(),
  maxTotalScore: z.string().optional(),
});

export type PeriodicEvaluationFilterFormValues = z.infer<
  typeof periodicEvaluationFilterSchema
>;

/*****************************************************************************************
 * COMPONENT
 *****************************************************************************************/
interface PeriodicEvaluationFilterSheetProps {
  /** Slide‑over visibility */
  isOpen: boolean;
  /** Close panel handler */
  onClose: () => void;
  /** Show skeleton / spinner while outer data grid fetches */
  isLoading?: boolean;
  /** Optional: fire immediately after URL is patched so parent can refetch */
  onFiltersApply: (filters: any[], joinOperator: "and" | "or") => void; // ✅ 필터 전달 콜백
}

export function PeriodicEvaluationFilterSheet({
  isOpen,
  onClose,
  isLoading = false,
  onFiltersApply,
}: PeriodicEvaluationFilterSheetProps) {
  /** Router (needed only for pathname) */
  const router = useRouter();

  /** Track pending state while we update URL */
  const [isPending, startTransition] = useTransition();
  const [joinOperator, setJoinOperator] = useState<"and" | "or">("and")


  /** React‑Hook‑Form */
  const form = useForm<PeriodicEvaluationFilterFormValues>({
    resolver: zodResolver(periodicEvaluationFilterSchema),
    defaultValues: {
      evaluationYear: new Date().getFullYear().toString(),
      division: "",
      status: "",
      domesticForeign: "",
      materialType: "",
      vendorCode: "",
      vendorName: "",
      documentsSubmitted: "",
      evaluationGrade: "",
      finalGrade: "",
      minTotalScore: "",
      maxTotalScore: "",
    },
  });


  /*****************************************************************************************
   * 3️⃣  Submit → build filter array → push to URL (and reset page=1)
   *****************************************************************************************/
  async function onSubmit(data: PeriodicEvaluationFilterFormValues) {
    startTransition(() => {
      try {
        const newFilters: any[] = [];

        const pushFilter = (
          id: string,
          value: any,
          type: "text" | "select" | "number" | "boolean",
          operator: "eq" | "iLike" | "gte" | "lte"
        ) => {
          newFilters.push({ id, value, type, operator, rowId: generateId() });
        };

        if (data.evaluationYear?.trim())
          pushFilter("evaluationYear", Number(data.evaluationYear), "number", "eq");

        if (data.division?.trim())
          pushFilter("division", data.division.trim(), "select", "eq");

        if (data.status?.trim())
          pushFilter("status", data.status.trim(), "select", "eq");

        if (data.domesticForeign?.trim())
          pushFilter("domesticForeign", data.domesticForeign.trim(), "select", "eq");

        if (data.materialType?.trim())
          pushFilter("materialType", data.materialType.trim(), "select", "eq");

        if (data.vendorCode?.trim())
          pushFilter("vendorCode", data.vendorCode.trim(), "text", "iLike");

        if (data.vendorName?.trim())
          pushFilter("vendorName", data.vendorName.trim(), "text", "iLike");

        if (data.documentsSubmitted?.trim())
          pushFilter(
            "documentsSubmitted",
            data.documentsSubmitted.trim() === "true",
            "boolean",
            "eq"
          );

        if (data.evaluationGrade?.trim())
          pushFilter("evaluationGrade", data.evaluationGrade.trim(), "select", "eq");

        if (data.finalGrade?.trim())
          pushFilter("finalGrade", data.finalGrade.trim(), "select", "eq");

        if (data.minTotalScore?.trim())
          pushFilter("totalScore", Number(data.minTotalScore), "number", "gte");

        if (data.maxTotalScore?.trim())
          pushFilter("totalScore", Number(data.maxTotalScore), "number", "lte");

        setJoinOperator(joinOperator);


        onFiltersApply(newFilters, joinOperator);
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error("정기평가 필터 적용 오류:", err);
      }
    });
  }

  /*****************************************************************************************
   * 4️⃣  Reset → clear form & URL
   *****************************************************************************************/
  async function handleReset() {
    form.reset({
      evaluationYear: new Date().getFullYear().toString(),
      division: "",
      status: "",
      domesticForeign: "",
      materialType: "",
      vendorCode: "",
      vendorName: "",
      documentsSubmitted: "",
      evaluationGrade: "",
      finalGrade: "",
      minTotalScore: "",
      maxTotalScore: "",
    });

    onFiltersApply([], "and");
    setJoinOperator("and");

  }

  /*****************************************************************************************
   * 5️⃣  RENDER
   *****************************************************************************************/
  if (!isOpen) return null;

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

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

      {/* Form */}
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-col h-full">
          {/* Scrollable 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}
                          disabled={isPending}
                          className={cn(field.value && "pr-8", "bg-white")}
                        />
                        {field.value && (
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={(e) => {
                              e.stopPropagation();
                              form.setValue("evaluationYear", "");
                            }}
                            disabled={isPending}
                            className="absolute right-0 top-0 h-full px-2"
                          >
                            <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}
                      disabled={isPending}
                    >
                      <FormControl>
                        <SelectTrigger className={cn(field.value && "pr-8", "bg-white")}>
                          <div className="flex w-full justify-between">
                            <SelectValue placeholder="구분 선택" />
                            {field.value && (
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="-mr-2 h-4 w-4"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  form.setValue("division", "");
                                }}
                                disabled={isPending}
                              >
                                <X className="size-3" />
                              </Button>
                            )}
                          </div>
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {EVALUATION_TARGET_FILTER_OPTIONS.DIVISIONS.map((opt) => (
                          <SelectItem key={opt.value} value={opt.value}>
                            {opt.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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

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

              {/* 벤더 코드 */}
              <FormField
                control={form.control}
                name="vendorCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>벤더 코드</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="벤더 코드 입력"
                          {...field}
                          disabled={isPending}
                          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", "");
                            }}
                            disabled={isPending}
                          >
                            <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}
                          disabled={isPending}
                          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", "");
                            }}
                            disabled={isPending}
                          >
                            <X className="size-3.5" />
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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

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

              {/* 점수 범위 */}
              <div className="grid grid-cols-2 gap-2">
                <FormField
                  control={form.control}
                  name="minTotalScore"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>최소점수</FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type="number"
                            step="0.1"
                            placeholder="최소"
                            {...field}
                            disabled={isPending}
                            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("minTotalScore", "");
                              }}
                              disabled={isPending}
                            >
                              <X className="size-3.5" />
                            </Button>
                          )}
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="maxTotalScore"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>최대점수</FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type="number"
                            step="0.1"
                            placeholder="최대"
                            {...field}
                            disabled={isPending}
                            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("maxTotalScore", "");
                              }}
                              disabled={isPending}
                            >
                              <X className="size-3.5" />
                            </Button>
                          )}
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>
          </div>

          {/* Footer buttons */}
          <div className="shrink-0 p-4">
            <div className="flex justify-end gap-2">
              <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="mr-2 size-4" />
                {isPending || isLoading ? "조회 중..." : "조회"}
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </div>
  );
}
