"use client"

import { useEffect, useTransition, useState, useRef } from "react"
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 { Checkbox } from "@/components/ui/checkbox"

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

// 필터 스키마 정의 (기술영업 벤더에 맞게 수정)
const filterSchema = z.object({
  vendorCode: z.string().optional(),
  vendorName: z.string().optional(),
  country: z.string().optional(),
  status: z.string().optional(),
  techVendorType: z.array(z.string()).optional(),
  workTypes: z.array(z.string()).optional(),
})

// 상태 옵션 정의
const statusOptions = [
  { value: "ACTIVE", label: "활성 상태" },
  { value: "INACTIVE", label: "비활성 상태" },
  { value: "BLACKLISTED", label: "거래 금지" },
  { value: "PENDING_INVITE", label: "초대 대기" },
  { value: "INVITED", label: "초대 완료" },
  { value: "QUOTE_COMPARISON", label: "견적 비교" },
]

// 벤더 타입 옵션
const vendorTypeOptions = [
  { value: "조선", label: "조선" },
  { value: "해양TOP", label: "해양TOP" },
  { value: "해양HULL", label: "해양HULL" },
]

// 공종 옵션
const workTypeOptions = [
  // 조선 workTypes
  { value: "기장", label: "기장" },
  { value: "전장", label: "전장" },
  { value: "선실", label: "선실" },
  { value: "배관", label: "배관" },
  { value: "철의", label: "철의" },
  { value: "선체", label: "선체" },
  // 해양TOP workTypes
  { value: "TM", label: "TM" },
  { value: "TS", label: "TS" },
  { value: "TE", label: "TE" },
  { value: "TP", label: "TP" },
  { value: "TA", label: "TA" },
  // 해양HULL workTypes
  { value: "HA", label: "HA" },
  { value: "HE", label: "HE" },
  { value: "HH", label: "HH" },
  { value: "HM", label: "HM" },
  { value: "NC", label: "NC" },
  { value: "HO", label: "HO" },
  { value: "HP", label: "HP" },
]

type FilterFormValues = z.infer<typeof filterSchema>

interface TechVendorsFilterSheetProps {
  isOpen: boolean;
  onClose: () => void;
  onSearch?: () => void;
  isLoading?: boolean;
}

export function TechVendorsFilterSheet({
  isOpen,
  onSearch,
  isLoading = false
}: TechVendorsFilterSheetProps) {


  const [isPending, startTransition] = useTransition()

  // 초기화 상태 추가 - 폼 초기화 중에는 상태 변경을 방지
  const [isInitializing, setIsInitializing] = useState(false)
  // 마지막으로 적용된 필터를 추적하기 위한 ref
  const lastAppliedFilters = useRef<string>("")

  // nuqs로 URL 상태 관리 - 파라미터명을 'filters'로 변경하여 searchParamsCache와 일치
  const [filters] = useQueryState(
    "filters",
    getFiltersStateParser().withDefault([])
  )

  // joinOperator 설정
  const [joinOperator, setJoinOperator] = useQueryState(
    "joinOperator",
    parseAsStringEnum(["and", "or"]).withDefault("and")
  )

  // 폼 상태 초기화
  const form = useForm<FilterFormValues>({
    resolver: zodResolver(filterSchema),
    defaultValues: {
      vendorCode: "",
      vendorName: "",
      country: "",
      status: "",
      techVendorType: [],
      workTypes: [],
    },
  })

  // URL 필터에서 초기 폼 상태 설정
  useEffect(() => {
    const currentFiltersString = JSON.stringify(filters);

    if (isOpen && filters && filters.length > 0 && currentFiltersString !== lastAppliedFilters.current) {
      setIsInitializing(true);

      const formValues = { ...form.getValues() };
      let formUpdated = false;

      filters.forEach(filter => {
        if (filter.id === "techVendorType" && Array.isArray(filter.value)) {
          formValues.techVendorType = filter.value;
          formUpdated = true;
        } else if (filter.id === "workTypes" && Array.isArray(filter.value)) {
          formValues.workTypes = filter.value;
          formUpdated = true;
        } else if (filter.id in formValues) {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (formValues as any)[filter.id] = filter.value;
          formUpdated = true;
        }
      });

      if (formUpdated) {
        form.reset(formValues);
        lastAppliedFilters.current = currentFiltersString;
      }

      setIsInitializing(false);
    }
  }, [filters, isOpen, form])

  // 현재 적용된 필터 카운트
  const getActiveFilterCount = () => {
    return filters?.length || 0
  }

  // 폼 제출 핸들러
  async function onSubmit(data: FilterFormValues) {
    if (isInitializing) return;

    startTransition(async () => {
      try {
        const newFilters = []

        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.country?.trim()) {
          newFilters.push({
            id: "country",
            value: data.country.trim(),
            type: "text",
            operator: "iLike",
            rowId: generateId()
          })
        }

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

        if (data.techVendorType && data.techVendorType.length > 0) {
          newFilters.push({
            id: "techVendorType",
            value: data.techVendorType,
            type: "multi-select",
            operator: "eq",
            rowId: generateId()
          })
        }

        if (data.workTypes && data.workTypes.length > 0) {
          newFilters.push({
            id: "workTypes",
            value: data.workTypes,
            type: "multi-select",
            operator: "eq",
            rowId: generateId()
          })
        }

        // URL 수동 업데이트
        const currentUrl = new URL(window.location.href);
        const params = new URLSearchParams(currentUrl.search);
        
        // 기존 필터 관련 파라미터 제거
        params.delete('filters');
        params.delete('joinOperator');
        params.delete('page');
        
        // 새로운 필터 추가
        if (newFilters.length > 0) {
          params.set('filters', JSON.stringify(newFilters));
          params.set('joinOperator', joinOperator);
        }
        
        // 페이지를 1로 설정
        params.set('page', '1');
        
        const newUrl = `${currentUrl.pathname}?${params.toString()}`;
        
        // 페이지 완전 새로고침
        window.location.href = newUrl;

        // 마지막 적용된 필터 업데이트
        lastAppliedFilters.current = JSON.stringify(newFilters);

        if (onSearch) {
          onSearch();
        }
      } catch (error) {
        console.error("벤더 필터 적용 오류:", error);
      }
    })
  }

  // 필터 초기화 핸들러
  async function handleReset() {
    try {
      setIsInitializing(true);

      form.reset({
        vendorCode: "",
        vendorName: "",
        country: "",
        status: "",
        techVendorType: [],
        workTypes: [],
      });

      const currentUrl = new URL(window.location.href);
      const params = new URLSearchParams(currentUrl.search);

      params.delete('filters');
      params.delete('joinOperator');
      params.set('page', '1');

      const newUrl = `${currentUrl.pathname}?${params.toString()}`;
      window.location.href = newUrl;

      lastAppliedFilters.current = "";
      setIsInitializing(false);
    } catch (error) {
      console.error("벤더 필터 초기화 오류:", error);
      setIsInitializing(false);
    }
  }

  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>
        <div className="flex items-center gap-2">
          {getActiveFilterCount() > 0 && (
            <Badge variant="secondary" className="px-2 py-1">
              {getActiveFilterCount()}개 필터 적용됨
            </Badge>
          )}
        </div>
      </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)}
          disabled={isInitializing}
        >
          <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="vendorCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>벤더코드</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="벤더코드 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                          disabled={isInitializing}
                        />
                        {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={isInitializing}
                          >
                            <X className="size-3.5" />
                            <span className="sr-only">Clear</span>
                          </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")}
                          disabled={isInitializing}
                        />
                        {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={isInitializing}
                          >
                            <X className="size-3.5" />
                            <span className="sr-only">Clear</span>
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 국가 */}
              <FormField
                control={form.control}
                name="country"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>국가</FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="국가 입력"
                          {...field}
                          className={cn(field.value && "pr-8", "bg-white")}
                          disabled={isInitializing}
                        />
                        {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("country", "");
                            }}
                            disabled={isInitializing}
                          >
                            <X className="size-3.5" />
                            <span className="sr-only">Clear</span>
                          </Button>
                        )}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 상태 */}
              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>상태</FormLabel>
                    <Select
                      value={field.value}
                      onValueChange={field.onChange}
                      disabled={isInitializing}
                    >
                      <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", "");
                                }}
                                disabled={isInitializing}
                              >
                                <X className="size-3" />
                                <span className="sr-only">Clear</span>
                              </Button>
                            )}
                          </div>
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {statusOptions.map(option => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 벤더 타입 */}
              <FormField
                control={form.control}
                name="techVendorType"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>벤더 타입</FormLabel>
                    <div className="space-y-2">
                      {vendorTypeOptions.map((option) => (
                        <div key={option.value} className="flex items-center space-x-2">
                          <Checkbox
                            id={`vendorType-${option.value}`}
                            checked={field.value?.includes(option.value) || false}
                            onCheckedChange={(checked) => {
                              const updatedValue = checked
                                ? [...(field.value || []), option.value]
                                : (field.value || []).filter((value) => value !== option.value);
                              field.onChange(updatedValue);
                            }}
                            disabled={isInitializing}
                          />
                          <label
                            htmlFor={`vendorType-${option.value}`}
                            className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                          >
                            {option.label}
                          </label>
                        </div>
                      ))}
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 공종 */}
              <FormField
                control={form.control}
                name="workTypes"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>공종</FormLabel>
                    <div className="grid grid-cols-2 gap-2">
                      {workTypeOptions.map((option) => (
                        <div key={option.value} className="flex items-center space-x-2">
                          <Checkbox
                            id={`workType-${option.value}`}
                            checked={field.value?.includes(option.value) || false}
                            onCheckedChange={(checked) => {
                              const updatedValue = checked
                                ? [...(field.value || []), option.value]
                                : (field.value || []).filter((value) => value !== option.value);
                              field.onChange(updatedValue);
                            }}
                            disabled={isInitializing}
                          />
                          <label
                            htmlFor={`workType-${option.value}`}
                            className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                          >
                            {option.label}
                          </label>
                        </div>
                      ))}
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>

          {/* Action buttons */}
          <div className="shrink-0 border-t bg-white px-6 py-4">
            <div className="flex gap-2">
              <Button
                type="submit"
                className="flex-1"
                disabled={isPending || isInitializing || isLoading}
              >
                {isPending ? (
                  <>
                    <Search className="mr-2 h-4 w-4 animate-spin" />
                    검색 중...
                  </>
                ) : (
                  <>
                    <Search className="mr-2 h-4 w-4" />
                    검색
                  </>
                )}
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={handleReset}
                disabled={isPending || isInitializing || isLoading}
              >
                초기화
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </div>
  )
} 