"use client";

import { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ArrowLeft } from "lucide-react";
import { DepartmentStructure } from "@/components/admin/department/DepartmentStructure";
import { DepartmentMembers } from "@/components/admin/department/DepartmentMembers";
import type { Department } from "@/types/department";
import { getCompanyList } from "@/lib/api/company";

/**
 * 부서 관리 메인 페이지
 * 좌측: 부서 구조, 우측: 부서 인원
 */
export default function DepartmentManagementPage() {
  const params = useParams();
  const router = useRouter();
  const companyCode = params.companyCode as string;
  const [selectedDepartment, setSelectedDepartment] = useState<Department | null>(null);
  const [activeTab, setActiveTab] = useState<string>("structure");
  const [companyName, setCompanyName] = useState<string>("");
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  // 부서원 변경 시 부서 구조 새로고침
  const handleMemberChange = () => {
    setRefreshTrigger((prev) => prev + 1);
  };

  // 회사 정보 로드
  useEffect(() => {
    const loadCompanyInfo = async () => {
      const response = await getCompanyList();
      if (response.success && response.data) {
        const company = response.data.find((c) => c.company_code === companyCode);
        if (company) {
          setCompanyName(company.company_name);
        }
      }
    };
    loadCompanyInfo();
  }, [companyCode]);

  const handleBackToList = () => {
    router.push("/admin/userMng/companyList");
  };

  return (
    <div className="space-y-4">
      {/* 상단 헤더: 회사 정보 + 뒤로가기 */}
      <div className="flex items-center justify-between border-b pb-4">
        <div className="flex items-center gap-3">
          <Button variant="outline" size="sm" onClick={handleBackToList} className="h-9 gap-2">
            <ArrowLeft className="h-4 w-4" />
            회사 목록
          </Button>
          <div className="bg-border h-6 w-px" />
          <div>
            <h2 className="text-xl font-semibold">{companyName || companyCode}</h2>
            <p className="text-muted-foreground text-sm">부서 관리</p>
          </div>
        </div>
      </div>
      {/* 탭 네비게이션 (모바일용) */}
      <div className="lg:hidden">
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="structure">부서 구조</TabsTrigger>
            <TabsTrigger value="members">부서 인원</TabsTrigger>
          </TabsList>

          <TabsContent value="structure" className="mt-4">
            <DepartmentStructure
              companyCode={companyCode}
              selectedDepartment={selectedDepartment}
              onSelectDepartment={setSelectedDepartment}
              refreshTrigger={refreshTrigger}
            />
          </TabsContent>

          <TabsContent value="members" className="mt-4">
            <DepartmentMembers
              companyCode={companyCode}
              selectedDepartment={selectedDepartment}
              onMemberChange={handleMemberChange}
            />
          </TabsContent>
        </Tabs>
      </div>

      {/* 좌우 레이아웃 (데스크톱) */}
      <div className="hidden h-full gap-6 lg:flex">
        {/* 좌측: 부서 구조 (20%) */}
        <div className="w-[20%] border-r pr-6">
          <DepartmentStructure
            companyCode={companyCode}
            selectedDepartment={selectedDepartment}
            onSelectDepartment={setSelectedDepartment}
            refreshTrigger={refreshTrigger}
          />
        </div>

        {/* 우측: 부서 인원 (80%) */}
        <div className="w-[80%] pl-0">
          <DepartmentMembers
            companyCode={companyCode}
            selectedDepartment={selectedDepartment}
            onMemberChange={handleMemberChange}
          />
        </div>
      </div>
    </div>
  );
}
