"use client"

import * as React from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import {
  Tooltip,
  TooltipTrigger,
  TooltipContent,
} from "@/components/ui/tooltip"
import { Package2, FormInput } from "lucide-react"
import { useRouter, usePathname } from "next/navigation"
import { Skeleton } from "@/components/ui/skeleton"
import { type FormInfo } from "@/lib/forms/services"

interface PackageData {
  itemId: number
  itemName: string
}

interface SidebarProps extends React.HTMLAttributes<HTMLDivElement> {
  isCollapsed: boolean
  packages: PackageData[]
  selectedPackageId: number | null
  selectedProjectId: number | null
  selectedContractId: number | null
  onSelectPackage: (itemId: number) => void
  forms?: FormInfo[]
  onSelectForm: (formName: string) => void
  isLoadingForms?: boolean
  mode: "IM" | "ENG"
}

export function Sidebar({
  className,
  isCollapsed,
  packages,
  selectedPackageId,
  selectedProjectId,
  selectedContractId,
  onSelectPackage,
  forms,
  onSelectForm,
  isLoadingForms = false,
  mode = "IM",
}: SidebarProps) {
  const router = useRouter()
  const rawPathname = usePathname()
  const pathname = rawPathname ?? ""

  /**
   * ---------------------------
   * 1) URL에서 현재 패키지 / 폼 코드 추출
   * ---------------------------
   */
  const segments = pathname.split("/").filter(Boolean)

  let currentItemId: number | null = null
  let currentFormCode: string | null = null

  const tagIndex = segments.indexOf("tag")
  if (tagIndex !== -1 && segments[tagIndex + 1]) {
    currentItemId = parseInt(segments[tagIndex + 1], 10)
  }

  const formIndex = segments.indexOf("form")
  if (formIndex !== -1) {
    const itemSegment = segments[formIndex + 1]
    const codeSegment = segments[formIndex + 2]

    if (itemSegment) {
      currentItemId = parseInt(itemSegment, 10)
    }
    if (codeSegment) {
      currentFormCode = codeSegment
    }
  }

  /**
   * ---------------------------
   * 2) 패키지 클릭 핸들러 (IM 모드)
   * ---------------------------
   */
  const handlePackageClick = (itemId: number) => {
    // 상위 컴포넌트 상태 업데이트
    onSelectPackage(itemId)

    // 해당 태그 페이지로 라우팅
    // 예: /vendor-data/tag/123
    const baseSegments = segments.slice(0, segments.indexOf("vendor-data") + 1).join("/")
    router.push(`/${baseSegments}/tag/${itemId}`)
  }

  /**
   * ---------------------------
   * 3) 폼 클릭 핸들러 (IM 모드만 사용)
   * ---------------------------
   */
  const handleFormClick = (form: FormInfo) => {
    // IM 모드에서만 사용
    if (selectedPackageId === null) return;
    
    onSelectForm(form.formName)
    
    const baseSegments = segments.slice(0, segments.indexOf("vendor-data") + 1).join("/")
    router.push(`/${baseSegments}/form/${selectedPackageId}/${form.formCode}/${selectedProjectId}/${selectedContractId}?mode=${mode}`)
  }

  /**
   * ---------------------------
   * 4) 패키지 클릭 핸들러 (ENG 모드)
   * ---------------------------
   */
  const handlePackageUnderFormClick = (form: FormInfo, pkg: PackageData) => {
    onSelectForm(form.formName)
    onSelectPackage(pkg.itemId)
    
    const baseSegments = segments.slice(0, segments.indexOf("vendor-data") + 1).join("/")
    router.push(`/${baseSegments}/form/${pkg.itemId}/${form.formCode}/${selectedProjectId}/${selectedContractId}?mode=${mode}`)
  }

  return (
    <div className={cn("pb-12", className)}>
      <div className="space-y-4 py-4">
        {/* ---------- 패키지(Items) 목록 - IM 모드에서만 표시 ---------- */}
        {mode === "IM" && (
          <>
            <div className="py-1">
              <h2 className="relative px-7 text-lg font-semibold tracking-tight">
                {isCollapsed ? "P" : "Package Lists"}
              </h2>
              <ScrollArea className="h-[150px] px-1">
                <div className="space-y-1 p-2">
                  {packages.map((pkg) => {
                    const isActive = pkg.itemId === currentItemId

                    return (
                      <div key={pkg.itemId}>
                        {isCollapsed ? (
                          <Tooltip delayDuration={0}>
                            <TooltipTrigger asChild>
                              <Button
                                variant="ghost"
                                className={cn(
                                  "w-full justify-start font-normal",
                                  isActive && "bg-accent text-accent-foreground"
                                )}
                                onClick={() => handlePackageClick(pkg.itemId)}
                              >
                                <Package2 className="mr-2 h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent side="right">
                              {pkg.itemName}
                            </TooltipContent>
                          </Tooltip>
                        ) : (
                          <Button
                            variant="ghost"
                            className={cn(
                              "w-full justify-start font-normal",
                              isActive && "bg-accent text-accent-foreground"
                            )}
                            onClick={() => handlePackageClick(pkg.itemId)}
                          >
                            <Package2 className="mr-2 h-4 w-4" />
                            {pkg.itemName}
                          </Button>
                        )}
                      </div>
                    )
                  })}
                </div>
              </ScrollArea>
            </div>
            <Separator />
          </>
        )}

        {/* ---------- 폼 목록 (IM 모드) / 패키지와 폼 목록 (ENG 모드) ---------- */}
        <div className="py-1">
          <h2 className="relative px-7 text-lg font-semibold tracking-tight">
            {isCollapsed 
              ? (mode === "IM" ? "F" : "P") 
              : (mode === "IM" ? "Form Lists" : "Package Lists")
            }
          </h2>
          <ScrollArea className={cn(
            "px-1",
            mode === "IM" ? "h-[300px]" : "h-[450px]"
          )}>
            <div className="space-y-1 p-2">
              {isLoadingForms ? (
                Array.from({ length: 3 }).map((_, index) => (
                  <div key={`form-skeleton-${index}`} className="px-2 py-1.5">
                    <Skeleton className="h-8 w-full" />
                  </div>
                ))
              ) : mode === "IM" ? (
                // =========== IM 모드: 폼만 표시 ===========
                !forms || forms.length === 0 ? (
                  <p className="text-sm text-muted-foreground px-2">
                    (No forms loaded)
                  </p>
                ) : (
                  forms
                    .sort((a, b) => a.formName.localeCompare(b.formName))
                    .map((form) => {
                    const isFormActive = form.formCode === currentFormCode
                    const isDisabled = currentItemId === null

                    return isCollapsed ? (
                      <Tooltip key={form.formCode} delayDuration={0}>
                        <TooltipTrigger asChild>
                          <Button
                            variant="ghost"
                            className={cn(
                              "w-full justify-start font-normal",
                              isFormActive && "bg-accent text-accent-foreground"
                            )}
                            onClick={() => handleFormClick(form)}
                            disabled={isDisabled}
                          >
                            <FormInput className="mr-2 h-4 w-4" />
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent side="right">
                          {form.formName}
                        </TooltipContent>
                      </Tooltip>
                    ) : (
                      <Button
                        key={form.formCode}
                        variant="ghost"
                        className={cn(
                          "w-full justify-start font-normal",
                          isFormActive && "bg-accent text-accent-foreground"
                        )}
                        onClick={() => handleFormClick(form)}
                        disabled={isDisabled}
                      >
                        <FormInput className="mr-2 h-4 w-4" />
                        {form.formName}
                      </Button>
                    )
                  })
                )
              ) : (
                // =========== ENG 모드: 패키지 > 폼 계층 구조 ===========
                packages.length === 0 ? (
                  <p className="text-sm text-muted-foreground px-2">
                    (No packages loaded)
                  </p>
                ) : (
                  packages.map((pkg) => (
                    <div key={pkg.itemId} className="space-y-1">
                      {isCollapsed ? (
                        <Tooltip delayDuration={0}>
                          <TooltipTrigger asChild>
                            <div className="px-2 py-1">
                              <Package2 className="h-4 w-4" />
                            </div>
                          </TooltipTrigger>
                          <TooltipContent side="right">
                            {pkg.itemName}
                          </TooltipContent>
                        </Tooltip>
                      ) : (
                        <>
                          {/* 패키지 이름 (클릭 불가능한 라벨) */}
                          <div className="flex items-center px-2 py-1 text-sm font-medium">
                            <Package2 className="mr-2 h-4 w-4" />
                            {pkg.itemName}
                          </div>
                          
                          {/* 폼 목록 바로 표시 */}
                          <div className="ml-6 space-y-1">
                            {!forms || forms.length === 0 ? (
                              <p className="text-xs text-muted-foreground px-2 py-1">
                                No forms available
                              </p>
                            ) : (
                              forms
                                .sort((a, b) => a.formName.localeCompare(b.formName))
                                .map((form) => {
                                const isFormPackageActive = 
                                  pkg.itemId === currentItemId && 
                                  form.formCode === currentFormCode

                                return (
                                  <Button
                                    key={`${pkg.itemId}-${form.formCode}`}
                                    variant="ghost"
                                    size="sm"
                                    className={cn(
                                      "w-full justify-start font-normal text-sm",
                                      isFormPackageActive && "bg-accent text-accent-foreground"
                                    )}
                                    onClick={() => handlePackageUnderFormClick(form, pkg)}
                                  >
                                    <FormInput className="mr-2 h-3 w-3" />
                                    {form.formName}
                                  </Button>
                                )
                              })
                            )}
                          </div>
                        </>
                      )}
                    </div>
                  ))
                )
              )}
            </div>
          </ScrollArea>
        </div>
      </div>
    </div>
  )
}