'use client';

import { useState, useCallback, useMemo, useRef } from 'react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { CurrencyInput } from '@/components/ui/currency-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { SearchableSelectionModal } from '@/components/organisms/SearchableSelectionModal';
import { Save, Search, UserPlus, Plus, X, RefreshCw, Loader2 } from 'lucide-react';
import { getEmployees } from '@/components/hr/EmployeeManagement/actions';
import type { Employee } from '@/components/hr/EmployeeManagement/types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { createPayroll, getPayrollSettings } from './actions';
import type { NameAmountItem, PayrollSettings } from './types';
import { formatCurrency } from './types';

// ===== Props =====
interface SalaryRegistrationDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  defaultYear: number;
  defaultMonth: number;
  onSaved: () => void;
}

// ===== 컴포넌트 =====
export function SalaryRegistrationDialog({
  open,
  onOpenChange,
  defaultYear,
  defaultMonth,
  onSaved,
}: SalaryRegistrationDialogProps) {
  // 사원 선택
  const [employeeSearchOpen, setEmployeeSearchOpen] = useState(false);
  const [selectedEmployee, setSelectedEmployee] = useState<Employee | null>(null);
  const searchOpenRef = useRef(false);

  // 급여 기본 정보
  const [year, setYear] = useState(defaultYear);
  const [month, setMonth] = useState(defaultMonth);
  const [baseSalary, setBaseSalary] = useState(0);
  const [overtimePay, setOvertimePay] = useState(0);
  const [mealAllowance, setMealAllowance] = useState(200000); // 식대(비과세) 기본 20만원

  // 추가 수당
  const [allowances, setAllowances] = useState<NameAmountItem[]>([]);

  // 법정 공제
  const [pension, setPension] = useState(0);
  const [healthInsurance, setHealthInsurance] = useState(0);
  const [longTermCare, setLongTermCare] = useState(0);
  const [employmentInsurance, setEmploymentInsurance] = useState(0);
  const [incomeTax, setIncomeTax] = useState(0);
  const [residentTax, setResidentTax] = useState(0);

  // 추가 공제
  const [deductions, setDeductions] = useState<NameAmountItem[]>([]);

  // 공제대상가족수
  const [dependents, setDependents] = useState(1);

  // 비고
  const [note, setNote] = useState('');

  // 로딩
  const [isSaving, setIsSaving] = useState(false);
  const [isCalculating, setIsCalculating] = useState(false);

  // 설정 (재계산용)
  const [settings, setSettings] = useState<PayrollSettings | null>(null);

  // 검색 모달 열기/닫기
  const handleSearchOpenChange = useCallback((isOpen: boolean) => {
    if (isOpen) {
      searchOpenRef.current = true;
    } else {
      setTimeout(() => { searchOpenRef.current = false; }, 300);
    }
    setEmployeeSearchOpen(isOpen);
  }, []);

  // 설정 로드 (재계산용)
  const loadSettings = useCallback(async () => {
    if (settings) return settings;
    const result = await getPayrollSettings();
    if (result.success && result.data) {
      setSettings(result.data);
      return result.data;
    }
    return null;
  }, [settings]);

  // 공제 자동 계산 (백엔드 PayrollSetting 계산 로직과 동일)
  const calculateDeductions = useCallback(async (salary: number) => {
    setIsCalculating(true);
    try {
      const s = await loadSettings();
      if (!s) {
        toast.error('급여 설정을 불러올 수 없습니다.');
        return;
      }

      // 국민연금: baseSalary 기준, 상/하한액 반영 (round)
      const pensionBase = Math.min(Math.max(salary, s.pensionMinSalary), s.pensionMaxSalary);
      const newPension = Math.round(pensionBase * s.pensionRate / 100);

      // 건강보험 (round)
      const newHealth = Math.round(salary * s.healthInsuranceRate / 100);

      // 장기요양보험 (건강보험료의 %) — 화면에는 분리 표시
      const newLongTermCare = Math.round(newHealth * s.longTermCareRate / 100);

      // 고용보험 (round)
      const newEmployment = Math.round(salary * s.employmentInsuranceRate / 100);

      // 근로소득세 (기본 요율 0%, 수동 입력 방식)
      const newIncomeTax = Math.round(salary * s.incomeTaxRate / 100);

      // 지방소득세 (근로소득세의 %)
      const newResidentTax = Math.round(newIncomeTax * s.residentTaxRate / 100);

      setPension(newPension);
      setHealthInsurance(newHealth);
      setLongTermCare(newLongTermCare);
      setEmploymentInsurance(newEmployment);
      setIncomeTax(newIncomeTax);
      setResidentTax(newResidentTax);

      toast.success('공제 항목이 재계산되었습니다.');
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('공제 계산 중 오류가 발생했습니다.');
    } finally {
      setIsCalculating(false);
    }
  }, [loadSettings]);

  // 사원 선택 시 기본값 세팅
  const handleSelectEmployee = useCallback(async (employee: Employee) => {
    setSelectedEmployee(employee);
    handleSearchOpenChange(false);

    // 기본급 세팅 (연봉 / 12)
    const monthlySalary = employee.salary ? Math.round(employee.salary / 12) : 0;
    setBaseSalary(monthlySalary);

    // baseSalary 기준으로 공제 자동 계산 (백엔드 로직과 동일)
    if (monthlySalary > 0) {
      await calculateDeductions(monthlySalary);
    }
  }, [handleSearchOpenChange, calculateDeductions]);

  // 사원 검색 fetch
  const handleFetchEmployees = useCallback(async (query: string) => {
    const result = await getEmployees({
      q: query || undefined,
      status: 'active',
      per_page: 50,
    });
    return result.data || [];
  }, []);

  // 검색어 유효성
  const isValidSearch = useCallback((query: string) => {
    if (!query || !query.trim()) return false;
    return /[a-zA-Z가-힣ㄱ-ㅎㅏ-ㅣ0-9]/.test(query);
  }, []);

  // ===== 합계 계산 =====
  const allowancesTotal = useMemo(
    () => allowances.reduce((sum, a) => sum + a.amount, 0),
    [allowances]
  );

  const grossSalary = useMemo(
    () => baseSalary + overtimePay + mealAllowance + allowancesTotal,
    [baseSalary, overtimePay, mealAllowance, allowancesTotal]
  );

  const taxBase = useMemo(
    () => Math.max(0, grossSalary - mealAllowance),
    [grossSalary, mealAllowance]
  );

  const legalDeductionsTotal = useMemo(
    () => pension + healthInsurance + longTermCare + employmentInsurance + incomeTax + residentTax,
    [pension, healthInsurance, longTermCare, employmentInsurance, incomeTax, residentTax]
  );

  const extraDeductionsTotal = useMemo(
    () => deductions.reduce((sum, d) => sum + d.amount, 0),
    [deductions]
  );

  const totalDeductions = legalDeductionsTotal + extraDeductionsTotal;
  const netSalary = grossSalary - totalDeductions;

  // ===== 수당 추가/삭제 =====
  const addAllowance = useCallback(() => {
    setAllowances(prev => [...prev, { name: '', amount: 0 }]);
  }, []);

  const removeAllowance = useCallback((idx: number) => {
    setAllowances(prev => prev.filter((_, i) => i !== idx));
  }, []);

  const updateAllowance = useCallback((idx: number, field: 'name' | 'amount', value: string | number) => {
    setAllowances(prev => prev.map((item, i) =>
      i === idx ? { ...item, [field]: value } : item
    ));
  }, []);

  // ===== 공제 추가/삭제 =====
  const addDeduction = useCallback(() => {
    setDeductions(prev => [...prev, { name: '', amount: 0 }]);
  }, []);

  const removeDeduction = useCallback((idx: number) => {
    setDeductions(prev => prev.filter((_, i) => i !== idx));
  }, []);

  const updateDeduction = useCallback((idx: number, field: 'name' | 'amount', value: string | number) => {
    setDeductions(prev => prev.map((item, i) =>
      i === idx ? { ...item, [field]: value } : item
    ));
  }, []);

  // ===== 재계산 (baseSalary 기준 — 백엔드 동일) =====
  const handleRecalculate = useCallback(() => {
    calculateDeductions(baseSalary);
  }, [calculateDeductions, baseSalary]);

  // 저장 가능 여부
  const canSave = selectedEmployee && baseSalary > 0;

  // 저장
  const handleSave = useCallback(async () => {
    if (!selectedEmployee || !canSave) return;
    setIsSaving(true);

    try {
      const result = await createPayroll({
        user_id: selectedEmployee.userId || parseInt(selectedEmployee.id, 10),
        pay_year: year,
        pay_month: month,
        base_salary: baseSalary,
        overtime_pay: overtimePay,
        bonus: mealAllowance,
        allowances: allowances.filter(a => a.name && a.amount > 0),
        pension,
        health_insurance: healthInsurance,
        long_term_care: longTermCare,
        employment_insurance: employmentInsurance,
        income_tax: incomeTax,
        resident_tax: residentTax,
        deductions: deductions.filter(d => d.name && d.amount > 0),
        note: note || undefined,
      });

      if (result.success) {
        toast.success('급여가 등록되었습니다.');
        onSaved();
        onOpenChange(false);
      } else {
        toast.error(result.error || '급여 등록에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('급여 등록에 실패했습니다.');
    } finally {
      setIsSaving(false);
    }
  }, [
    selectedEmployee, canSave, year, month, baseSalary, overtimePay, mealAllowance,
    allowances, pension, healthInsurance, longTermCare, employmentInsurance,
    incomeTax, residentTax, deductions, note, onSaved, onOpenChange,
  ]);

  // 다이얼로그 닫힐 때 초기화
  const handleOpenChange = useCallback((isOpen: boolean) => {
    if (!isOpen && searchOpenRef.current) return;
    if (!isOpen) {
      setSelectedEmployee(null);
      setBaseSalary(0);
      setOvertimePay(0);
      setMealAllowance(200000);
      setAllowances([]);
      setPension(0);
      setHealthInsurance(0);
      setLongTermCare(0);
      setEmploymentInsurance(0);
      setIncomeTax(0);
      setResidentTax(0);
      setDeductions([]);
      setDependents(1);
      setNote('');
    } else {
      setYear(defaultYear);
      setMonth(defaultMonth);
    }
    onOpenChange(isOpen);
  }, [onOpenChange, defaultYear, defaultMonth]);

  // 년도/월 옵션
  const yearOptions = useMemo(() => {
    const cy = new Date().getFullYear();
    return Array.from({ length: 3 }, (_, i) => cy - 1 + i);
  }, []);
  const monthOptions = Array.from({ length: 12 }, (_, i) => i + 1);

  return (
    <>
      <Dialog open={open} onOpenChange={handleOpenChange}>
        <DialogContent className="sm:max-w-[750px] max-h-[90vh] overflow-y-auto p-4 sm:p-6">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <UserPlus className="h-5 w-5" />
              급여 등록
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-5">
            {/* ===== 기본 정보 ===== */}
            <div className="bg-muted/50 rounded-lg p-3 sm:p-4">
              <h3 className="font-semibold mb-3">기본 정보</h3>

              {/* 사원 선택 */}
              {!selectedEmployee ? (
                <Button
                  variant="outline"
                  className="w-full h-12 border-dashed"
                  onClick={() => handleSearchOpenChange(true)}
                >
                  <Search className="h-4 w-4 mr-2" />
                  사원 검색 (클릭하여 선택)
                </Button>
              ) : (
                <div className="space-y-3">
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">사번</span>
                      <p className="font-medium">{selectedEmployee.employeeCode || selectedEmployee.id}</p>
                    </div>
                    <div>
                      <span className="text-muted-foreground">이름</span>
                      <p className="font-medium">{selectedEmployee.name}</p>
                    </div>
                    <div>
                      <span className="text-muted-foreground">부서</span>
                      <p className="font-medium">
                        {selectedEmployee.departmentPositions?.[0]?.departmentName || '-'}
                      </p>
                    </div>
                    <div>
                      <span className="text-muted-foreground">직급</span>
                      <p className="font-medium">{selectedEmployee.rank || '-'}</p>
                    </div>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-xs text-muted-foreground"
                    onClick={() => handleSearchOpenChange(true)}
                  >
                    다른 사원 선택
                  </Button>
                </div>
              )}

              {/* 지급 연월 */}
              <div className="grid grid-cols-2 gap-3 mt-4">
                <div>
                  <span className="text-sm text-muted-foreground block mb-1">년도</span>
                  <Select value={String(year)} onValueChange={(v) => setYear(Number(v))}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {yearOptions.map(y => (
                        <SelectItem key={y} value={String(y)}>{y}년</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <span className="text-sm text-muted-foreground block mb-1">월</span>
                  <Select value={String(month)} onValueChange={(v) => setMonth(Number(v))}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {monthOptions.map(m => (
                        <SelectItem key={m} value={String(m)}>{m}월</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            {/* ===== 지급 항목 ===== */}
            <div className="border rounded-lg p-3 sm:p-4">
              <h3 className="font-semibold mb-3 text-blue-600">지급 항목</h3>
              <div className="space-y-3">
                {/* 기본급 */}
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">기본급</span>
                  <CurrencyInput
                    value={baseSalary}
                    onChange={(v) => setBaseSalary(v ?? 0)}
                    className="flex-1 h-8 text-right"
                  />
                </div>
                {selectedEmployee?.salary && (
                  <p className="text-xs text-muted-foreground ml-32">
                    연봉 {formatCurrency(selectedEmployee.salary)}원 기준
                  </p>
                )}
                {/* 고정연장근로수당 */}
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">고정연장근로수당</span>
                  <CurrencyInput
                    value={overtimePay}
                    onChange={(v) => setOvertimePay(v ?? 0)}
                    className="flex-1 h-8 text-right"
                  />
                </div>
                {/* 식대(비과세) */}
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">식대(비과세)</span>
                  <CurrencyInput
                    value={mealAllowance}
                    onChange={(v) => setMealAllowance(v ?? 0)}
                    className="flex-1 h-8 text-right"
                  />
                </div>

                <Separator />

                {/* 추가 수당 */}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">추가 수당</span>
                  <Button variant="outline" size="sm" className="h-7 text-xs" onClick={addAllowance}>
                    <Plus className="h-3 w-3 mr-1" />
                    추가
                  </Button>
                </div>
                {allowances.map((item, idx) => (
                  <div key={idx} className="flex items-center gap-2">
                    <Input
                      placeholder="수당명"
                      value={item.name}
                      onChange={(e) => updateAllowance(idx, 'name', e.target.value)}
                      className="w-32 h-8 text-sm"
                    />
                    <CurrencyInput
                      value={item.amount}
                      onChange={(v) => updateAllowance(idx, 'amount', v ?? 0)}
                      className="flex-1 h-8 text-right"
                    />
                    <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0" onClick={() => removeAllowance(idx)}>
                      <X className="h-3 w-3" />
                    </Button>
                  </div>
                ))}

                <Separator />

                {/* 합계 */}
                <div className="flex items-center justify-between font-semibold text-blue-600">
                  <span>총 지급액</span>
                  <span>{formatCurrency(grossSalary)}원</span>
                </div>
                <div className="flex items-center justify-between text-sm text-muted-foreground">
                  <span>과세표준 (식대 제외)</span>
                  <span>{formatCurrency(taxBase)}원</span>
                </div>
              </div>
            </div>

            {/* ===== 공제 항목 ===== */}
            <div className="border rounded-lg p-3 sm:p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="font-semibold text-red-600">공제 항목</h3>
                <Button
                  variant="outline"
                  size="sm"
                  className="h-7 text-xs"
                  onClick={handleRecalculate}
                  disabled={isCalculating || !selectedEmployee}
                >
                  {isCalculating ? (
                    <Loader2 className="h-3 w-3 mr-1 animate-spin" />
                  ) : (
                    <RefreshCw className="h-3 w-3 mr-1" />
                  )}
                  재계산
                </Button>
              </div>

              <div className="space-y-3">
                {/* 공제대상가족수 */}
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">공제대상 가족수</span>
                  <Input
                    type="number"
                    min={1}
                    value={dependents}
                    onChange={(e) => setDependents(parseInt(e.target.value) || 1)}
                    className="w-20 h-8 text-right text-sm"
                  />
                  <span className="text-xs text-muted-foreground">명 (본인 포함)</span>
                </div>

                <Separator />

                {/* 4대보험 */}
                <p className="text-xs text-muted-foreground font-medium">4대보험</p>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">국민연금</span>
                  <CurrencyInput value={pension} onChange={(v) => setPension(v ?? 0)} className="flex-1 h-8 text-right" />
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">건강보험</span>
                  <CurrencyInput value={healthInsurance} onChange={(v) => setHealthInsurance(v ?? 0)} className="flex-1 h-8 text-right" />
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">장기요양보험</span>
                  <CurrencyInput value={longTermCare} onChange={(v) => setLongTermCare(v ?? 0)} className="flex-1 h-8 text-right" />
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">고용보험</span>
                  <CurrencyInput value={employmentInsurance} onChange={(v) => setEmploymentInsurance(v ?? 0)} className="flex-1 h-8 text-right" />
                </div>

                <Separator />

                {/* 세금 */}
                <p className="text-xs text-muted-foreground font-medium">세금</p>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">근로소득세</span>
                  <CurrencyInput value={incomeTax} onChange={(v) => setIncomeTax(v ?? 0)} className="flex-1 h-8 text-right" />
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground w-32 shrink-0">지방소득세</span>
                  <CurrencyInput value={residentTax} onChange={(v) => setResidentTax(v ?? 0)} className="flex-1 h-8 text-right" />
                </div>

                <Separator />

                {/* 추가 공제 */}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">추가 공제</span>
                  <Button variant="outline" size="sm" className="h-7 text-xs" onClick={addDeduction}>
                    <Plus className="h-3 w-3 mr-1" />
                    추가
                  </Button>
                </div>
                {deductions.map((item, idx) => (
                  <div key={idx} className="flex items-center gap-2">
                    <Input
                      placeholder="공제명"
                      value={item.name}
                      onChange={(e) => updateDeduction(idx, 'name', e.target.value)}
                      className="w-32 h-8 text-sm"
                    />
                    <CurrencyInput
                      value={item.amount}
                      onChange={(v) => updateDeduction(idx, 'amount', v ?? 0)}
                      className="flex-1 h-8 text-right"
                    />
                    <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0" onClick={() => removeDeduction(idx)}>
                      <X className="h-3 w-3" />
                    </Button>
                  </div>
                ))}

                <Separator />

                {/* 공제 합계 */}
                <div className="flex items-center justify-between font-semibold text-red-600">
                  <span>총 공제액</span>
                  <span>-{formatCurrency(totalDeductions)}원</span>
                </div>
              </div>
            </div>

            {/* ===== 합계 ===== */}
            <div className="bg-primary/5 border-2 border-primary/20 rounded-lg p-3 sm:p-4">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4 text-center">
                <div>
                  <span className="text-xs sm:text-sm text-muted-foreground block">총 지급액</span>
                  <span className="text-sm sm:text-lg font-semibold text-blue-600">
                    {formatCurrency(grossSalary)}원
                  </span>
                </div>
                <div>
                  <span className="text-xs sm:text-sm text-muted-foreground block">총 공제액</span>
                  <span className="text-sm sm:text-lg font-semibold text-red-600">
                    -{formatCurrency(totalDeductions)}원
                  </span>
                </div>
                <div>
                  <span className="text-xs sm:text-sm text-muted-foreground block">실수령액</span>
                  <span className="text-base sm:text-xl font-bold text-primary">
                    {formatCurrency(netSalary)}원
                  </span>
                </div>
              </div>
            </div>

            {/* ===== 비고 ===== */}
            <div>
              <span className="text-sm text-muted-foreground block mb-1">비고</span>
              <Textarea
                placeholder="비고 입력..."
                value={note}
                onChange={(e) => setNote(e.target.value)}
                rows={2}
              />
            </div>
          </div>

          <DialogFooter className="mt-6">
            <Button variant="outline" onClick={() => handleOpenChange(false)}>
              취소
            </Button>
            <Button onClick={handleSave} disabled={!canSave || isSaving} className="gap-2">
              {isSaving ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Save className="h-4 w-4" />
              )}
              등록
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 사원 검색 모달 */}
      <SearchableSelectionModal<Employee>
        open={employeeSearchOpen}
        onOpenChange={handleSearchOpenChange}
        title="사원 검색"
        searchPlaceholder="사원명, 사원코드 검색..."
        fetchData={handleFetchEmployees}
        keyExtractor={(emp) => emp.id}
        validateSearch={isValidSearch}
        invalidSearchMessage="한글, 영문 또는 숫자 1자 이상 입력하세요"
        emptyQueryMessage="사원명 또는 사원코드를 입력하세요"
        loadingMessage="사원 검색 중..."
        dialogClassName="sm:max-w-[500px]"
        infoText={(items, isLoading) =>
          !isLoading ? (
            <span className="text-xs text-gray-400 text-right block">
              총 {items.length}명
            </span>
          ) : null
        }
        mode="single"
        onSelect={handleSelectEmployee}
        renderItem={(employee) => (
          <div className="p-3 hover:bg-blue-50 transition-colors">
            <div className="flex items-center justify-between">
              <div>
                <span className="font-semibold text-gray-900">{employee.name}</span>
                {employee.employeeCode && (
                  <span className="text-xs text-gray-400 ml-2">({employee.employeeCode})</span>
                )}
              </div>
              {employee.rank && (
                <span className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded">
                  {employee.rank}
                </span>
              )}
            </div>
            {employee.departmentPositions.length > 0 && (
              <p className="text-sm text-gray-600 mt-1">
                {employee.departmentPositions
                  .map(dp => `${dp.departmentName} / ${dp.positionName}`)
                  .join(', ')}
              </p>
            )}
            {employee.salary && (
              <p className="text-xs text-gray-400 mt-1">
                연봉: {Number(employee.salary).toLocaleString()}원
              </p>
            )}
          </div>
        )}
      />
    </>
  );
}
