"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 { List, FormInput, FileText } from "lucide-react"
import { Skeleton } from "@/components/ui/skeleton"
import { getEngineeringForms, getIMForms } from "@/lib/tags-plant/service"

interface FormInfo {
  formCode: string
  formName: string
}

interface SidebarProps extends React.HTMLAttributes<HTMLDivElement> {
  isCollapsed: boolean
  selectedPackageCode: string | null
  selectedFormCode: string | null
  currentMode: "master" | "engineering" | "im" | null
  projectCode: string // 추가
  onMasterTagListClick: () => void
  onEngineeringFormClick: (formCode: string) => void
  onIMFormClick: (formCode: string) => void
}

export function Sidebar({
  className,
  isCollapsed,
  selectedPackageCode,
  selectedFormCode,
  currentMode,
  projectCode, // 추가
  onMasterTagListClick,
  onEngineeringFormClick,
  onIMFormClick,
}: SidebarProps) {
  const [engineeringForms, setEngineeringForms] = React.useState<FormInfo[]>([])
  const [imForms, setIMForms] = React.useState<FormInfo[]>([])
  const [isLoadingEngineering, setIsLoadingEngineering] = React.useState(false)
  const [isLoadingIM, setIsLoadingIM] = React.useState(false)


  // Engineering 폼 로드
  React.useEffect(() => {
    if (!selectedPackageCode || !projectCode) {
      setEngineeringForms([])
      return
    }

    const loadEngineeringForms = async () => {
      setIsLoadingEngineering(true)
      try {
        const result = await getEngineeringForms(projectCode, selectedPackageCode)
        setEngineeringForms(result)
      } catch (error) {
        console.error("Engineering 폼 로딩 오류:", error)
        setEngineeringForms([])
      } finally {
        setIsLoadingEngineering(false)
      }
    }

    loadEngineeringForms()
  }, [selectedPackageCode, projectCode])

  // IM 폼 로드
  React.useEffect(() => {
    if (!selectedPackageCode || !projectCode) {
      setIMForms([])
      return
    }

    const loadIMForms = async () => {
      setIsLoadingIM(true)
      try {
        const result = await getIMForms(projectCode, selectedPackageCode)
        setIMForms(result)
      } catch (error) {
        console.error("IM 폼 로딩 오류:", error)
        setIMForms([])
      } finally {
        setIsLoadingIM(false)
      }
    }

    loadIMForms()
  }, [selectedPackageCode, projectCode])

  const isMasterActive = currentMode === "master"
  const isPackageSelected = selectedPackageCode !== null

  return (
    <div className={cn("pb-12", className)}>
      <div className="space-y-4 py-4">
        {/* Master Tag List */}
        <div className="py-1">
          <h2 className="relative px-7 text-lg font-semibold tracking-tight">
            {isCollapsed ? "M" : "Master"}
          </h2>
          <div className="space-y-1 p-2">
            {isCollapsed ? (
              <Tooltip delayDuration={0}>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    className={cn(
                      "w-full justify-start font-normal",
                      isMasterActive && "bg-accent text-accent-foreground"
                    )}
                    onClick={onMasterTagListClick}
                    disabled={!isPackageSelected}
                  >
                    <List className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent side="right">
                  Master Tag List
                </TooltipContent>
              </Tooltip>
            ) : (
              <Button
                variant="ghost"
                className={cn(
                  "w-full justify-start font-normal",
                  isMasterActive && "bg-accent text-accent-foreground"
                )}
                onClick={onMasterTagListClick}
                disabled={!isPackageSelected}
              >
                <List className="mr-2 h-4 w-4" />
                Master Tag List
              </Button>
            )}
          </div>
        </div>

        <Separator />

        {/* Engineering Forms */}
        <div className="py-1">
          <h2 className="relative px-7 text-lg font-semibold tracking-tight">
            {isCollapsed ? "E" : "Engineering"}
          </h2>
          <ScrollArea className="h-[250px] px-1">
            <div className="space-y-1 p-2">
              {isLoadingEngineering ? (
                Array.from({ length: 3 }).map((_, index) => (
                  <div key={`eng-skeleton-${index}`} className="px-2 py-1.5">
                    <Skeleton className="h-8 w-full" />
                  </div>
                ))
              ) : !isPackageSelected ? (
                <p className="text-sm text-muted-foreground px-2">
                  Select a package first
                </p>
              ) : engineeringForms.length === 0 ? (
                <p className="text-sm text-muted-foreground px-2">
                  No forms available
                </p>
              ) : (
                engineeringForms.map((form) => {
                  const isActive = 
                    currentMode === "engineering" && 
                    form.formCode === selectedFormCode

                  return isCollapsed ? (
                    <Tooltip key={form.formCode} delayDuration={0}>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          className={cn(
                            "w-full justify-start font-normal",
                            isActive && "bg-accent text-accent-foreground"
                          )}
                          onClick={() => onEngineeringFormClick(form.formCode)}
                        >
                          <FormInput className="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",
                        isActive && "bg-accent text-accent-foreground"
                      )}
                      onClick={() => onEngineeringFormClick(form.formCode)}
                    >
                      <FormInput className="mr-2 h-4 w-4" />
                      {form.formName}
                    </Button>
                  )
                })
              )}
            </div>
          </ScrollArea>
        </div>

        <Separator />

        {/* IM Forms */}
        <div className="py-1">
          <h2 className="relative px-7 text-lg font-semibold tracking-tight">
            {isCollapsed ? "I" : "IM"}
          </h2>
          <ScrollArea className="h-[250px] px-1">
            <div className="space-y-1 p-2">
              {isLoadingIM ? (
                Array.from({ length: 3 }).map((_, index) => (
                  <div key={`im-skeleton-${index}`} className="px-2 py-1.5">
                    <Skeleton className="h-8 w-full" />
                  </div>
                ))
              ) : !isPackageSelected ? (
                <p className="text-sm text-muted-foreground px-2">
                  Select a package first
                </p>
              ) : imForms.length === 0 ? (
                <p className="text-sm text-muted-foreground px-2">
                  No forms available
                </p>
              ) : (
                imForms.map((form) => {
                  const isActive = 
                    currentMode === "im" && 
                    form.formCode === selectedFormCode

                  return isCollapsed ? (
                    <Tooltip key={form.formCode} delayDuration={0}>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          className={cn(
                            "w-full justify-start font-normal",
                            isActive && "bg-accent text-accent-foreground"
                          )}
                          onClick={() => onIMFormClick(form.formCode)}
                        >
                          <FileText className="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",
                        isActive && "bg-accent text-accent-foreground"
                      )}
                      onClick={() => onIMFormClick(form.formCode)}
                    >
                      <FileText className="mr-2 h-4 w-4" />
                      {form.formName}
                    </Button>
                  )
                })
              )}
            </div>
          </ScrollArea>
        </div>
      </div>
    </div>
  )
}