'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
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 {
  Save,
  Pencil,
  X,
  Trash2,
  CheckCircle,
  Undo2,
  Banknote,
  Plus,
  Loader2,
} from 'lucide-react';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import {
  updatePayroll,
  deletePayroll,
  confirmPayroll,
  unconfirmPayroll,
  payPayroll,
  unpayPayroll,
} from './actions';
import type { PayrollDetail, NameAmountItem } from './types';
import {
  PAYROLL_STATUS_LABELS,
  PAYROLL_STATUS_COLORS,
  formatCurrency,
} from './types';

// ===== Props =====
interface SalaryDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  payrollDetail: PayrollDetail | null;
  onSaved: () => void;
}

// ===== 컴포넌트 =====
export function SalaryDetailDialog({
  open,
  onOpenChange,
  payrollDetail,
  onSaved,
}: SalaryDetailDialogProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [isActionLoading, setIsActionLoading] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState(false);
  const [confirmConfirm, setConfirmConfirm] = useState(false);
  const [payConfirm, setPayConfirm] = useState(false);

  // 편집 상태
  const [baseSalary, setBaseSalary] = useState(0);
  const [overtimePay, setOvertimePay] = useState(0);
  const [bonus, setBonus] = useState(0);
  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 [note, setNote] = useState('');

  // 데이터 → 편집 상태 동기화
  useEffect(() => {
    if (payrollDetail) {
      setBaseSalary(payrollDetail.baseSalary);
      setOvertimePay(payrollDetail.overtimePay);
      setBonus(payrollDetail.bonus);
      setAllowances([...payrollDetail.allowances]);
      setPension(payrollDetail.pension);
      setHealthInsurance(payrollDetail.healthInsurance);
      setLongTermCare(payrollDetail.longTermCare);
      setEmploymentInsurance(payrollDetail.employmentInsurance);
      setIncomeTax(payrollDetail.incomeTax);
      setResidentTax(payrollDetail.residentTax);
      setDeductions([...payrollDetail.deductions]);
      setNote(payrollDetail.note || '');
      setIsEditing(false);
    }
  }, [payrollDetail]);

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

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

  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 updateAllowanceItem = 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 updateDeductionItem = useCallback((idx: number, field: 'name' | 'amount', value: string | number) => {
    setDeductions(prev => prev.map((item, i) =>
      i === idx ? { ...item, [field]: value } : item
    ));
  }, []);

  // ===== 편집 취소 =====
  const handleCancelEdit = useCallback(() => {
    if (!payrollDetail) return;
    setBaseSalary(payrollDetail.baseSalary);
    setOvertimePay(payrollDetail.overtimePay);
    setBonus(payrollDetail.bonus);
    setAllowances([...payrollDetail.allowances]);
    setPension(payrollDetail.pension);
    setHealthInsurance(payrollDetail.healthInsurance);
    setLongTermCare(payrollDetail.longTermCare);
    setEmploymentInsurance(payrollDetail.employmentInsurance);
    setIncomeTax(payrollDetail.incomeTax);
    setResidentTax(payrollDetail.residentTax);
    setDeductions([...payrollDetail.deductions]);
    setNote(payrollDetail.note || '');
    setIsEditing(false);
  }, [payrollDetail]);

  // ===== 저장 =====
  const handleSave = useCallback(async () => {
    if (!payrollDetail) return;
    setIsActionLoading(true);
    try {
      const result = await updatePayroll(payrollDetail.id, {
        base_salary: baseSalary,
        overtime_pay: overtimePay,
        bonus,
        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('급여가 수정되었습니다.');
        setIsEditing(false);
        onSaved();
      } else {
        toast.error(result.error || '급여 수정에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('급여 수정에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [
    payrollDetail, baseSalary, overtimePay, bonus, allowances,
    pension, healthInsurance, longTermCare, employmentInsurance,
    incomeTax, residentTax, deductions, note, onSaved,
  ]);

  // ===== 삭제 =====
  const handleDelete = useCallback(async () => {
    if (!payrollDetail) return;
    setDeleteConfirm(false);
    setIsActionLoading(true);
    try {
      const result = await deletePayroll(payrollDetail.id);
      if (result.success) {
        toast.success('급여가 삭제되었습니다.');
        onOpenChange(false);
        onSaved();
      } else {
        toast.error(result.error || '급여 삭제에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('급여 삭제에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [payrollDetail, onOpenChange, onSaved]);

  // ===== 확정 =====
  const handleConfirm = useCallback(async () => {
    if (!payrollDetail) return;
    setConfirmConfirm(false);
    setIsActionLoading(true);
    try {
      const result = await confirmPayroll(payrollDetail.id);
      if (result.success) {
        toast.success('급여가 확정되었습니다.');
        onSaved();
      } else {
        toast.error(result.error || '급여 확정에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('급여 확정에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [payrollDetail, onSaved]);

  // ===== 확정 취소 =====
  const handleUnconfirm = useCallback(async () => {
    if (!payrollDetail) return;
    setIsActionLoading(true);
    try {
      const result = await unconfirmPayroll(payrollDetail.id);
      if (result.success) {
        toast.success('확정이 취소되었습니다.');
        onSaved();
      } else {
        toast.error(result.error || '확정 취소에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('확정 취소에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [payrollDetail, onSaved]);

  // ===== 지급 처리 =====
  const handlePay = useCallback(async () => {
    if (!payrollDetail) return;
    setPayConfirm(false);
    setIsActionLoading(true);
    try {
      const result = await payPayroll(payrollDetail.id);
      if (result.success) {
        toast.success('지급 처리되었습니다.');
        onSaved();
      } else {
        toast.error(result.error || '지급 처리에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('지급 처리에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [payrollDetail, onSaved]);

  // ===== 지급 취소 =====
  const handleUnpay = useCallback(async () => {
    if (!payrollDetail) return;
    setIsActionLoading(true);
    try {
      const result = await unpayPayroll(payrollDetail.id);
      if (result.success) {
        toast.success('지급이 취소되었습니다.');
        onSaved();
      } else {
        toast.error(result.error || '지급 취소에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('지급 취소에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [payrollDetail, onSaved]);

  if (!payrollDetail) return null;

  const isDraft = payrollDetail.status === 'draft';
  const isConfirmed = payrollDetail.status === 'confirmed';
  const isPaid = payrollDetail.status === 'paid';

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[750px] max-h-[90vh] overflow-y-auto p-4 sm:p-6">
          <DialogHeader>
            <DialogTitle className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
              <span className="truncate">{payrollDetail.userName} 급여 상세</span>
              <div className="flex items-center gap-2 shrink-0 mr-6">
                <Badge className={PAYROLL_STATUS_COLORS[payrollDetail.status]}>
                  {PAYROLL_STATUS_LABELS[payrollDetail.status]}
                </Badge>
                {isDraft && !isEditing && (
                  <Button
                    variant="outline"
                    size="sm"
                    className="h-7 text-xs"
                    onClick={() => setIsEditing(true)}
                    disabled={isActionLoading}
                  >
                    <Pencil className="h-3 w-3 mr-1" />
                    수정
                  </Button>
                )}
                {isEditing && (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-7 text-xs"
                    onClick={handleCancelEdit}
                  >
                    <X className="h-3 w-3 mr-1" />
                    취소
                  </Button>
                )}
              </div>
            </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>
              <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">{payrollDetail.userName}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">부서</span>
                  <p className="font-medium">{payrollDetail.department}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">직급</span>
                  <p className="font-medium">{payrollDetail.rank}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">직책</span>
                  <p className="font-medium">{payrollDetail.position}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">지급월</span>
                  <p className="font-medium">{payrollDetail.payYear}년 {payrollDetail.payMonth}월</p>
                </div>
                {payrollDetail.confirmedAt && (
                  <div>
                    <span className="text-muted-foreground">확정일</span>
                    <p className="font-medium">{payrollDetail.confirmedAt.slice(0, 10)}</p>
                  </div>
                )}
                {payrollDetail.paidAt && (
                  <div>
                    <span className="text-muted-foreground">지급일</span>
                    <p className="font-medium">{payrollDetail.paidAt.slice(0, 10)}</p>
                  </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-2 text-sm">
                <DetailRow label="기본급" value={baseSalary} editing={isEditing} onChange={setBaseSalary} />
                <DetailRow label="고정연장근로수당" value={overtimePay} editing={isEditing} onChange={setOvertimePay} />
                <DetailRow label="식대(비과세)" value={bonus} editing={isEditing} onChange={setBonus} />

                {/* 추가 수당 */}
                {(allowances.length > 0 || isEditing) && <Separator />}
                {isEditing && (
                  <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) => (
                  isEditing ? (
                    <div key={idx} className="flex items-center gap-2">
                      <Input
                        placeholder="수당명"
                        value={item.name}
                        onChange={(e) => updateAllowanceItem(idx, 'name', e.target.value)}
                        className="w-32 h-8 text-sm"
                      />
                      <CurrencyInput
                        value={item.amount}
                        onChange={(v) => updateAllowanceItem(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>
                  ) : (
                    <DetailRow key={idx} label={item.name} value={item.amount} editing={false} />
                  )
                ))}

                <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-xs text-muted-foreground">
                  <span>과세표준 (식대 제외)</span>
                  <span>{formatCurrency(Math.max(0, grossSalary - bonus))}원</span>
                </div>
              </div>
            </div>

            {/* ===== 공제 항목 ===== */}
            <div className="border rounded-lg p-3 sm:p-4">
              <h3 className="font-semibold mb-3 text-red-600">공제 항목</h3>
              <div className="space-y-2 text-sm">
                <p className="text-xs text-muted-foreground font-medium">4대보험</p>
                <DetailRow label="국민연금" value={pension} editing={isEditing} onChange={setPension} color="text-red-600" />
                <DetailRow label="건강보험" value={healthInsurance} editing={isEditing} onChange={setHealthInsurance} color="text-red-600" />
                <DetailRow label="장기요양보험" value={longTermCare} editing={isEditing} onChange={setLongTermCare} color="text-red-600" />
                <DetailRow label="고용보험" value={employmentInsurance} editing={isEditing} onChange={setEmploymentInsurance} color="text-red-600" />

                <Separator />
                <p className="text-xs text-muted-foreground font-medium">세금</p>
                <DetailRow label="근로소득세" value={incomeTax} editing={isEditing} onChange={setIncomeTax} color="text-red-600" />
                <DetailRow label="지방소득세" value={residentTax} editing={isEditing} onChange={setResidentTax} color="text-red-600" />

                {/* 추가 공제 */}
                {(deductions.length > 0 || isEditing) && <Separator />}
                {isEditing && (
                  <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) => (
                  isEditing ? (
                    <div key={idx} className="flex items-center gap-2">
                      <Input
                        placeholder="공제명"
                        value={item.name}
                        onChange={(e) => updateDeductionItem(idx, 'name', e.target.value)}
                        className="w-32 h-8 text-sm"
                      />
                      <CurrencyInput
                        value={item.amount}
                        onChange={(v) => updateDeductionItem(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>
                  ) : (
                    <DetailRow key={idx} label={item.name} value={item.amount} editing={false} color="text-red-600" />
                  )
                ))}

                <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>
              {isEditing ? (
                <Textarea
                  value={note}
                  onChange={(e) => setNote(e.target.value)}
                  rows={2}
                  placeholder="비고 입력..."
                />
              ) : (
                <p className="text-sm p-2 bg-muted/30 rounded min-h-[2rem]">
                  {payrollDetail.note || '-'}
                </p>
              )}
            </div>
          </div>

          {/* ===== 하단 버튼 ===== */}
          <DialogFooter className="mt-6 flex-wrap gap-2">
            {/* 좌측: 상태 액션 버튼 */}
            <div className="flex gap-2 mr-auto">
              {isDraft && (
                <>
                  <Button
                    variant="outline"
                    size="sm"
                    className="text-red-600 border-red-200 hover:bg-red-50"
                    onClick={() => setDeleteConfirm(true)}
                    disabled={isActionLoading}
                  >
                    <Trash2 className="h-4 w-4 mr-1" />
                    삭제
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    className="text-blue-600 border-blue-200 hover:bg-blue-50"
                    onClick={() => setConfirmConfirm(true)}
                    disabled={isActionLoading}
                  >
                    <CheckCircle className="h-4 w-4 mr-1" />
                    확정
                  </Button>
                </>
              )}
              {isConfirmed && (
                <>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleUnconfirm}
                    disabled={isActionLoading}
                  >
                    <Undo2 className="h-4 w-4 mr-1" />
                    확정 취소
                  </Button>
                  <Button
                    size="sm"
                    className="bg-green-600 hover:bg-green-700"
                    onClick={() => setPayConfirm(true)}
                    disabled={isActionLoading}
                  >
                    <Banknote className="h-4 w-4 mr-1" />
                    지급 처리
                  </Button>
                </>
              )}
              {isPaid && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleUnpay}
                  disabled={isActionLoading}
                >
                  <Undo2 className="h-4 w-4 mr-1" />
                  지급 취소
                </Button>
              )}
            </div>

            {/* 우측: 닫기/저장 */}
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              닫기
            </Button>
            {isEditing && (
              <Button onClick={handleSave} disabled={isActionLoading} className="gap-2">
                {isActionLoading ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Save className="h-4 w-4" />
                )}
                저장
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ===== 삭제 확인 ===== */}
      <AlertDialog open={deleteConfirm} onOpenChange={setDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>급여 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              {payrollDetail.userName}님의 {payrollDetail.payYear}년 {payrollDetail.payMonth}월 급여를 삭제하시겠습니까?
              이 작업은 되돌릴 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700">삭제</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* ===== 확정 확인 ===== */}
      <AlertDialog open={confirmConfirm} onOpenChange={setConfirmConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>급여 확정</AlertDialogTitle>
            <AlertDialogDescription>
              {payrollDetail.userName}님의 급여를 확정하시겠습니까?
              확정 후에는 수정이 불가하며 확정 취소가 필요합니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handleConfirm}>확정</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* ===== 지급 확인 ===== */}
      <AlertDialog open={payConfirm} onOpenChange={setPayConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>지급 처리</AlertDialogTitle>
            <AlertDialogDescription>
              {payrollDetail.userName}님에게 {formatCurrency(netSalary)}원을 지급 처리하시겠습니까?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handlePay} className="bg-green-600 hover:bg-green-700">지급</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

// ===== 상세 행 컴포넌트 =====
function DetailRow({
  label,
  value,
  editing,
  onChange,
  color,
}: {
  label: string;
  value: number;
  editing: boolean;
  onChange?: (value: number) => void;
  color?: string;
}) {
  return (
    <div className="flex items-center gap-2">
      <span className="text-muted-foreground w-32 shrink-0">{label}</span>
      <div className="flex-1 text-right">
        {editing && onChange ? (
          <CurrencyInput
            value={value}
            onChange={(v) => onChange(v ?? 0)}
            className="w-full h-7 text-sm text-right"
          />
        ) : (
          <span className={color}>{formatCurrency(value)}원</span>
        )}
      </div>
    </div>
  );
}
