'use client';

import { useState, useEffect } from 'react';
import { Plus, Minus } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import type { VacationUsageRecord, VacationAdjustment, AdjustableVacationType } from './types';
import { VACATION_TYPE_LABELS } from './types';

interface VacationAdjustDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  record: VacationUsageRecord | null;
  onSave: (adjustments: VacationAdjustment[]) => void;
}

interface AdjustmentState {
  annual: number;
  monthly: number;
  reward: number;
  other: number;
}

export function VacationAdjustDialog({
  open,
  onOpenChange,
  record,
  onSave,
}: VacationAdjustDialogProps) {
  const [adjustments, setAdjustments] = useState<AdjustmentState>({
    annual: 0,
    monthly: 0,
    reward: 0,
    other: 0,
  });

  // 다이얼로그가 열릴 때 조정값 초기화
  useEffect(() => {
    if (open) {
      setAdjustments({
        annual: 0,
        monthly: 0,
        reward: 0,
        other: 0,
      });
    }
  }, [open]);

  // 조정값 증가
  const handleIncrease = (type: AdjustableVacationType) => {
    setAdjustments(prev => ({
      ...prev,
      [type]: prev[type] + 1,
    }));
  };

  // 조정값 감소
  const handleDecrease = (type: AdjustableVacationType) => {
    setAdjustments(prev => ({
      ...prev,
      [type]: prev[type] - 1,
    }));
  };

  // 조정값 직접 입력
  const handleInputChange = (type: AdjustableVacationType, value: string) => {
    const numValue = parseInt(value, 10);
    if (!isNaN(numValue)) {
      setAdjustments(prev => ({
        ...prev,
        [type]: numValue,
      }));
    } else if (value === '' || value === '-') {
      setAdjustments(prev => ({
        ...prev,
        [type]: 0,
      }));
    }
  };

  // 저장 핸들러
  const handleSave = () => {
    const adjustmentList: VacationAdjustment[] = [];

    (Object.keys(adjustments) as AdjustableVacationType[]).forEach((type) => {
      if (adjustments[type] !== 0) {
        adjustmentList.push({
          vacationType: type,
          adjustment: adjustments[type],
        });
      }
    });

    onSave(adjustmentList);
  };

  // 취소 핸들러
  const handleCancel = () => {
    onOpenChange(false);
  };

  if (!record) return null;

  const vacationTypes: AdjustableVacationType[] = ['annual', 'monthly', 'reward', 'other'];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>휴가 조정</DialogTitle>
        </DialogHeader>

        {/* 사원 정보 */}
        <div className="bg-muted/50 rounded-lg p-4 mb-4">
          <p className="text-sm text-muted-foreground">
            {record.department} / {record.employeeName} / {record.rank}
          </p>
        </div>

        {/* 조정 테이블 */}
        <div className="py-2">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[100px]">휴가종류</TableHead>
                <TableHead className="text-center">총일수</TableHead>
                <TableHead className="text-center">사용일수</TableHead>
                <TableHead className="text-center">잔여일수</TableHead>
                <TableHead className="text-center w-[150px]">조정</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {vacationTypes.map((type) => {
                const info = record[type];
                const adjustment = adjustments[type];
                const newTotal = info.total + adjustment;
                const newRemaining = info.remaining + adjustment;

                return (
                  <TableRow key={type}>
                    <TableCell className="font-medium">
                      {VACATION_TYPE_LABELS[type]}
                    </TableCell>
                    <TableCell className="text-center">
                      <span className={adjustment !== 0 ? 'line-through text-muted-foreground mr-2' : ''}>
                        {info.total}
                      </span>
                      {adjustment !== 0 && (
                        <span className={adjustment > 0 ? 'text-green-600' : 'text-red-600'}>
                          {newTotal}
                        </span>
                      )}
                    </TableCell>
                    <TableCell className="text-center">{info.used}</TableCell>
                    <TableCell className="text-center">
                      <span className={adjustment !== 0 ? 'line-through text-muted-foreground mr-2' : ''}>
                        {info.remaining}
                      </span>
                      {adjustment !== 0 && (
                        <span className={adjustment > 0 ? 'text-green-600' : 'text-red-600'}>
                          {newRemaining}
                        </span>
                      )}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center justify-center gap-1">
                        <Button
                          variant="outline"
                          size="icon"
                          className="h-8 w-8"
                          onClick={() => handleDecrease(type)}
                        >
                          <Minus className="h-4 w-4" />
                        </Button>
                        <Input
                          type="text"
                          value={adjustment}
                          onChange={(e) => handleInputChange(type, e.target.value)}
                          className="w-16 h-8 text-center"
                        />
                        <Button
                          variant="outline"
                          size="icon"
                          className="h-8 w-8"
                          onClick={() => handleIncrease(type)}
                        >
                          <Plus className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleCancel}>
            취소
          </Button>
          <Button onClick={handleSave}>
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
