import { useEffect, useState } from 'react';
import { X, RefreshCw } from 'lucide-react';
import { comms } from '@/communication';
import { JobReportTypeItem } from '@/types';
import { DevelopmentNotice } from '@/components/DevelopmentNotice';

interface JobreportTypeModalProps {
    isOpen: boolean;
    onClose: () => void;
    startDate: string;
    endDate: string;
    userId: string;
}

export function JobreportTypeModal({
    isOpen,
    onClose,
    startDate,
    endDate,
    userId,
}: JobreportTypeModalProps) {
    const [loading, setLoading] = useState(false);
    const [items, setItems] = useState<JobReportTypeItem[]>([]);

    useEffect(() => {
        if (isOpen && startDate && endDate) {
            loadData();
        }
    }, [isOpen, startDate, endDate, userId]);

    const loadData = async () => {
        setLoading(true);
        try {
            const response = await comms.getJobReportTypeList(startDate, endDate, userId);
            if (response.Success && response.Data) {
                setItems(response.Data);
            } else {
                setItems([]);
            }
        } catch (error) {
            console.error('업무형태별 집계 로드 오류:', error);
            setItems([]);
        } finally {
            setLoading(false);
        }
    };

    if (!isOpen) return null;

    const totalHrs = items.reduce((acc, item) => acc + (item.hrs || 0), 0);
    const totalOt = items.reduce((acc, item) => acc + (item.ot || 0), 0);

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm animate-fade-in">
            <div className="bg-gray-900 border border-white/10 rounded-2xl shadow-2xl w-full max-w-2xl overflow-hidden">
                {/* 헤더 */}
                <div className="px-6 py-4 border-b border-white/10 flex items-center justify-between bg-white/5">
                    <h3 className="text-lg font-semibold text-white">업무형태별 집계</h3>
                    <button
                        onClick={onClose}
                        className="text-white/50 hover:text-white transition-colors"
                    >
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* 컨텐츠 */}
                <div className="p-6">
                    <DevelopmentNotice />
                    <div className="mb-4 text-white/70 text-sm">
                        기간: {startDate} ~ {endDate}
                    </div>

                    <div className="overflow-hidden rounded-xl border border-white/10">
                        <table className="w-full">
                            <thead className="bg-white/10">
                                <tr>
                                    <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">업무형태</th>
                                    <th className="px-4 py-3 text-right text-xs font-medium text-white/70 uppercase">건수</th>
                                    <th className="px-4 py-3 text-right text-xs font-medium text-white/70 uppercase">시간</th>
                                    <th className="px-4 py-3 text-right text-xs font-medium text-white/70 uppercase">OT</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-white/10">
                                {loading ? (
                                    <tr>
                                        <td colSpan={4} className="px-4 py-8 text-center">
                                            <div className="flex items-center justify-center">
                                                <RefreshCw className="w-5 h-5 mr-2 animate-spin text-white/50" />
                                                <span className="text-white/50">데이터를 불러오는 중...</span>
                                            </div>
                                        </td>
                                    </tr>
                                ) : items.length === 0 ? (
                                    <tr>
                                        <td colSpan={4} className="px-4 py-8 text-center text-white/50">
                                            데이터가 없습니다.
                                        </td>
                                    </tr>
                                ) : (
                                    <>
                                        {items.map((item, index) => (
                                            <tr key={index} className="hover:bg-white/5 transition-colors">
                                                <td className="px-4 py-3 text-white text-sm">{item.type || '-'}</td>
                                                <td className="px-4 py-3 text-white text-sm text-right">{item.count}</td>
                                                <td className="px-4 py-3 text-white text-sm text-right">{item.hrs}h</td>
                                                <td className="px-4 py-3 text-white text-sm text-right">
                                                    {item.ot > 0 ? <span className="text-warning-400">{item.ot}h</span> : '-'}
                                                </td>
                                            </tr>
                                        ))}
                                        {/* 합계 */}
                                        <tr className="bg-white/5 font-semibold">
                                            <td className="px-4 py-3 text-white text-sm">합계</td>
                                            <td className="px-4 py-3 text-white text-sm text-right">
                                                {items.reduce((acc, item) => acc + item.count, 0)}
                                            </td>
                                            <td className="px-4 py-3 text-white text-sm text-right">{totalHrs}h</td>
                                            <td className="px-4 py-3 text-white text-sm text-right">
                                                {totalOt > 0 ? <span className="text-warning-400">{totalOt}h</span> : '-'}
                                            </td>
                                        </tr>
                                    </>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>

                {/* 푸터 */}
                <div className="px-6 py-4 border-t border-white/10 flex justify-end bg-white/5">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors"
                    >
                        닫기
                    </button>
                </div>
            </div>
        </div>
    );
}
