'use client';

import { useState, useEffect, useCallback } 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 { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import { CurrencyInput } from '@/components/ui/currency-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Save, Pencil, X } from 'lucide-react';
import type { SalaryDetail, PaymentStatus } from './types';
import {
  PAYMENT_STATUS_LABELS,
  PAYMENT_STATUS_COLORS,
  formatCurrency,
} from './types';

interface AllowanceEdits {
  positionAllowance: number;
  overtimeAllowance: number;
  mealAllowance: number;
  transportAllowance: number;
  otherAllowance: number;
}

interface SalaryDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  salaryDetail: SalaryDetail | null;
  onSave?: (updatedDetail: SalaryDetail, allowanceDetails?: Record<string, number>) => void;
}

export function SalaryDetailDialog({
  open,
  onOpenChange,
  salaryDetail,
  onSave,
}: SalaryDetailDialogProps) {
  const [editedStatus, setEditedStatus] = useState<PaymentStatus>('scheduled');
  const [hasChanges, setHasChanges] = useState(false);
  const [isEditingAllowances, setIsEditingAllowances] = useState(false);
  const [editedAllowances, setEditedAllowances] = useState<AllowanceEdits>({
    positionAllowance: 0,
    overtimeAllowance: 0,
    mealAllowance: 0,
    transportAllowance: 0,
    otherAllowance: 0,
  });

  // 다이얼로그가 열릴 때 상태 초기화
  useEffect(() => {
    if (salaryDetail) {
      setEditedStatus(salaryDetail.status);
      setEditedAllowances({
        positionAllowance: salaryDetail.allowances.positionAllowance,
        overtimeAllowance: salaryDetail.allowances.overtimeAllowance,
        mealAllowance: salaryDetail.allowances.mealAllowance,
        transportAllowance: salaryDetail.allowances.transportAllowance,
        otherAllowance: salaryDetail.allowances.otherAllowance,
      });
      setHasChanges(false);
      setIsEditingAllowances(false);
    }
  }, [salaryDetail]);

  // 변경 사항 확인
  const checkForChanges = useCallback(() => {
    if (!salaryDetail) return false;

    const statusChanged = editedStatus !== salaryDetail.status;
    const allowancesChanged =
      editedAllowances.positionAllowance !== salaryDetail.allowances.positionAllowance ||
      editedAllowances.overtimeAllowance !== salaryDetail.allowances.overtimeAllowance ||
      editedAllowances.mealAllowance !== salaryDetail.allowances.mealAllowance ||
      editedAllowances.transportAllowance !== salaryDetail.allowances.transportAllowance ||
      editedAllowances.otherAllowance !== salaryDetail.allowances.otherAllowance;

    return statusChanged || allowancesChanged;
  }, [salaryDetail, editedStatus, editedAllowances]);

  useEffect(() => {
    setHasChanges(checkForChanges());
  }, [checkForChanges]);

  if (!salaryDetail) return null;

  const handleStatusChange = (newStatus: PaymentStatus) => {
    setEditedStatus(newStatus);
  };

  const handleAllowanceChange = (field: keyof AllowanceEdits, value: string) => {
    const numValue = parseInt(value.replace(/,/g, ''), 10) || 0;
    setEditedAllowances(prev => ({
      ...prev,
      [field]: numValue,
    }));
  };

  // 수당 합계 계산
  const calculateTotalAllowance = () => {
    return Object.values(editedAllowances).reduce((sum, val) => sum + val, 0);
  };

  // 실지급액 계산
  const calculateNetPayment = () => {
    return salaryDetail.baseSalary + calculateTotalAllowance() - salaryDetail.totalDeduction;
  };

  const handleSave = () => {
    if (onSave && salaryDetail) {
      // allowance_details를 백엔드 형식으로 변환
      const allowanceDetails = {
        position_allowance: editedAllowances.positionAllowance,
        overtime_allowance: editedAllowances.overtimeAllowance,
        meal_allowance: editedAllowances.mealAllowance,
        transport_allowance: editedAllowances.transportAllowance,
        other_allowance: editedAllowances.otherAllowance,
      };

      const updatedDetail: SalaryDetail = {
        ...salaryDetail,
        status: editedStatus,
        allowances: editedAllowances,
        totalAllowance: calculateTotalAllowance(),
        netPayment: calculateNetPayment(),
      };

      onSave(updatedDetail, allowanceDetails);
    }
    setHasChanges(false);
    setIsEditingAllowances(false);
  };

  const handleToggleEdit = () => {
    if (isEditingAllowances) {
      // 편집 취소 - 원래 값으로 복원
      setEditedAllowances({
        positionAllowance: salaryDetail.allowances.positionAllowance,
        overtimeAllowance: salaryDetail.allowances.overtimeAllowance,
        mealAllowance: salaryDetail.allowances.mealAllowance,
        transportAllowance: salaryDetail.allowances.transportAllowance,
        otherAllowance: salaryDetail.allowances.otherAllowance,
      });
    }
    setIsEditingAllowances(!isEditingAllowances);
  };

  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="min-w-[140px] w-auto">
                <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={isEditingAllowances ? "default" : "outline"}
                  size="sm"
                  onClick={handleToggleEdit}
                  className="h-7 text-xs"
                >
                  {isEditingAllowances ? (
                    <>
                      <X className="h-3 w-3 mr-1" />
                      편집 취소
                    </>
                  ) : (
                    <>
                      <Pencil className="h-3 w-3 mr-1" />
                      지급항목 수정
                    </>
                  )}
                </Button>
              </div>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">본봉</span>
                  <span className="font-medium">{formatCurrency(salaryDetail.baseSalary)}원</span>
                </div>
                <Separator />
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">직책수당</span>
                  {isEditingAllowances ? (
                    <CurrencyInput
                      value={editedAllowances.positionAllowance}
                      onChange={(value) => handleAllowanceChange('positionAllowance', String(value ?? 0))}
                      className="w-32 h-7 text-sm"
                    />
                  ) : (
                    <span>{formatCurrency(editedAllowances.positionAllowance)}원</span>
                  )}
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">초과근무수당</span>
                  {isEditingAllowances ? (
                    <CurrencyInput
                      value={editedAllowances.overtimeAllowance}
                      onChange={(value) => handleAllowanceChange('overtimeAllowance', String(value ?? 0))}
                      className="w-32 h-7 text-sm"
                    />
                  ) : (
                    <span>{formatCurrency(editedAllowances.overtimeAllowance)}원</span>
                  )}
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">식대</span>
                  {isEditingAllowances ? (
                    <CurrencyInput
                      value={editedAllowances.mealAllowance}
                      onChange={(value) => handleAllowanceChange('mealAllowance', String(value ?? 0))}
                      className="w-32 h-7 text-sm"
                    />
                  ) : (
                    <span>{formatCurrency(editedAllowances.mealAllowance)}원</span>
                  )}
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">교통비</span>
                  {isEditingAllowances ? (
                    <CurrencyInput
                      value={editedAllowances.transportAllowance}
                      onChange={(value) => handleAllowanceChange('transportAllowance', String(value ?? 0))}
                      className="w-32 h-7 text-sm"
                    />
                  ) : (
                    <span>{formatCurrency(editedAllowances.transportAllowance)}원</span>
                  )}
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">기타수당</span>
                  {isEditingAllowances ? (
                    <CurrencyInput
                      value={editedAllowances.otherAllowance}
                      onChange={(value) => handleAllowanceChange('otherAllowance', String(value ?? 0))}
                      className="w-32 h-7 text-sm"
                    />
                  ) : (
                    <span>{formatCurrency(editedAllowances.otherAllowance)}원</span>
                  )}
                </div>
                <Separator />
                <div className="flex justify-between font-semibold text-blue-600">
                  <span>수당 합계</span>
                  <span>{formatCurrency(calculateTotalAllowance())}원</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-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(salaryDetail.baseSalary + calculateTotalAllowance())}원
                </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(salaryDetail.totalDeduction)}원
                </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(calculateNetPayment())}원
                </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>
  );
}
