'use client';

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Plus, Save } from 'lucide-react';
import type { SalaryDetail, PaymentStatus } from './types';
import {
  PAYMENT_STATUS_LABELS,
  PAYMENT_STATUS_COLORS,
  formatCurrency,
} from './types';

interface SalaryDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  salaryDetail: SalaryDetail | null;
  onSave?: (updatedDetail: SalaryDetail) => void;
  onAddPaymentItem?: () => void;
}

export function SalaryDetailDialog({
  open,
  onOpenChange,
  salaryDetail,
  onSave,
  onAddPaymentItem,
}: SalaryDetailDialogProps) {
  const [editedStatus, setEditedStatus] = useState<PaymentStatus>('scheduled');
  const [hasChanges, setHasChanges] = useState(false);

  // 다이얼로그가 열릴 때 상태 초기화
  useEffect(() => {
    if (salaryDetail) {
      setEditedStatus(salaryDetail.status);
      setHasChanges(false);
    }
  }, [salaryDetail]);

  if (!salaryDetail) return null;

  const handleStatusChange = (newStatus: PaymentStatus) => {
    setEditedStatus(newStatus);
    setHasChanges(newStatus !== salaryDetail.status);
  };

  const handleSave = () => {
    if (onSave && salaryDetail) {
      onSave({
        ...salaryDetail,
        status: editedStatus,
      });
    }
    setHasChanges(false);
  };

  const handleAddPaymentItem = () => {
    if (onAddPaymentItem) {
      onAddPaymentItem();
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              급여 수정 - {salaryDetail.employeeName}
            </div>
            {/* 상태 변경 셀렉트 박스 */}
            <Select
              value={editedStatus}
              onValueChange={(value) => handleStatusChange(value as PaymentStatus)}
            >
              <SelectTrigger className="w-[140px]">
                <SelectValue>
                  <Badge className={PAYMENT_STATUS_COLORS[editedStatus]}>
                    {PAYMENT_STATUS_LABELS[editedStatus]}
                  </Badge>
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="scheduled">
                  <Badge className={PAYMENT_STATUS_COLORS.scheduled}>
                    {PAYMENT_STATUS_LABELS.scheduled}
                  </Badge>
                </SelectItem>
                <SelectItem value="completed">
                  <Badge className={PAYMENT_STATUS_COLORS.completed}>
                    {PAYMENT_STATUS_LABELS.completed}
                  </Badge>
                </SelectItem>
              </SelectContent>
            </Select>
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          {/* 기본 정보 */}
          <div className="bg-muted/50 rounded-lg 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">{salaryDetail.employeeId}</p>
              </div>
              <div>
                <span className="text-muted-foreground">이름</span>
                <p className="font-medium">{salaryDetail.employeeName}</p>
              </div>
              <div>
                <span className="text-muted-foreground">부서</span>
                <p className="font-medium">{salaryDetail.department}</p>
              </div>
              <div>
                <span className="text-muted-foreground">직급</span>
                <p className="font-medium">{salaryDetail.rank}</p>
              </div>
              <div>
                <span className="text-muted-foreground">직책</span>
                <p className="font-medium">{salaryDetail.position}</p>
              </div>
              <div>
                <span className="text-muted-foreground">지급월</span>
                <p className="font-medium">{salaryDetail.year}년 {salaryDetail.month}월</p>
              </div>
              <div>
                <span className="text-muted-foreground">지급일</span>
                <p className="font-medium">{salaryDetail.paymentDate}</p>
              </div>
            </div>
          </div>

          {/* 급여 항목 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 수당 내역 */}
            <div className="border rounded-lg p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="font-semibold text-blue-600">수당 내역</h3>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleAddPaymentItem}
                  className="h-7 text-xs"
                >
                  <Plus className="h-3 w-3 mr-1" />
                  지급항목 추가
                </Button>
              </div>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">본봉</span>
                  <span className="font-medium">{formatCurrency(salaryDetail.baseSalary)}원</span>
                </div>
                <Separator />
                <div className="flex justify-between">
                  <span className="text-muted-foreground">직책수당</span>
                  <span>{formatCurrency(salaryDetail.allowances.positionAllowance)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">초과근무수당</span>
                  <span>{formatCurrency(salaryDetail.allowances.overtimeAllowance)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">식대</span>
                  <span>{formatCurrency(salaryDetail.allowances.mealAllowance)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">교통비</span>
                  <span>{formatCurrency(salaryDetail.allowances.transportAllowance)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">기타수당</span>
                  <span>{formatCurrency(salaryDetail.allowances.otherAllowance)}원</span>
                </div>
                <Separator />
                <div className="flex justify-between font-semibold text-blue-600">
                  <span>수당 합계</span>
                  <span>{formatCurrency(salaryDetail.totalAllowance)}원</span>
                </div>
              </div>
            </div>

            {/* 공제 내역 */}
            <div className="border rounded-lg p-4">
              <h3 className="font-semibold mb-3 text-red-600">공제 내역</h3>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">국민연금</span>
                  <span className="text-red-600">-{formatCurrency(salaryDetail.deductions.nationalPension)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">건강보험</span>
                  <span className="text-red-600">-{formatCurrency(salaryDetail.deductions.healthInsurance)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">장기요양보험</span>
                  <span className="text-red-600">-{formatCurrency(salaryDetail.deductions.longTermCare)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">고용보험</span>
                  <span className="text-red-600">-{formatCurrency(salaryDetail.deductions.employmentInsurance)}원</span>
                </div>
                <Separator />
                <div className="flex justify-between">
                  <span className="text-muted-foreground">소득세</span>
                  <span className="text-red-600">-{formatCurrency(salaryDetail.deductions.incomeTax)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">지방소득세</span>
                  <span className="text-red-600">-{formatCurrency(salaryDetail.deductions.localIncomeTax)}원</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">기타공제</span>
                  <span className="text-red-600">-{formatCurrency(salaryDetail.deductions.otherDeduction)}원</span>
                </div>
                <Separator />
                <div className="flex justify-between font-semibold text-red-600">
                  <span>공제 합계</span>
                  <span>-{formatCurrency(salaryDetail.totalDeduction)}원</span>
                </div>
              </div>
            </div>
          </div>

          {/* 지급 합계 */}
          <div className="bg-primary/5 border-2 border-primary/20 rounded-lg p-4">
            <div className="grid grid-cols-3 gap-4 text-center">
              <div>
                <span className="text-sm text-muted-foreground block">급여 총액</span>
                <span className="text-lg font-semibold text-blue-600">
                  {formatCurrency(salaryDetail.baseSalary + salaryDetail.totalAllowance)}원
                </span>
              </div>
              <div>
                <span className="text-sm text-muted-foreground block">공제 총액</span>
                <span className="text-lg font-semibold text-red-600">
                  -{formatCurrency(salaryDetail.totalDeduction)}원
                </span>
              </div>
              <div>
                <span className="text-sm text-muted-foreground block">실지급액</span>
                <span className="text-xl font-bold text-primary">
                  {formatCurrency(salaryDetail.netPayment)}원
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* 저장 버튼 */}
        <DialogFooter className="mt-6">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
          >
            취소
          </Button>
          <Button
            onClick={handleSave}
            disabled={!hasChanges}
            className="gap-2"
          >
            <Save className="h-4 w-4" />
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
