import { useState, useEffect } from 'react';
import { X, ChevronLeft, ChevronRight, Download } from 'lucide-react';
import { comms } from '@/communication';
import { HolidayItem } from '@/types';

interface JobReportDayDialogProps {
    isOpen: boolean;
    onClose: () => void;
    initialMonth?: string; // YYYY-MM format
}

interface DayColumn {
    day: number;
    dayOfWeek: string;
    isHoliday: boolean;
    holidayMemo?: string;
}

interface UserRow {
    uid: string;
    uname: string;
    processs: string;
    dailyData: Map<number, { hrs: number; ot: number; jobtype: string }>;
    totalHrs: number;
    totalOt: number;
    totalHolidayOt: number;
}

export function JobReportDayDialog({ isOpen, onClose, initialMonth }: JobReportDayDialogProps) {
    const [currentMonth, setCurrentMonth] = useState(initialMonth || new Date().toISOString().substring(0, 7));
    const [loading, setLoading] = useState(false);
    const [dayColumns, setDayColumns] = useState<DayColumn[]>([]);
    const [userRows, setUserRows] = useState<UserRow[]>([]);
    const [currentUserId, setCurrentUserId] = useState<string>('');
    const [canViewAll, setCanViewAll] = useState<boolean>(false);

    // 요일 배열
    const weekDays = ['일', '월', '화', '수', '목', '금', '토'];

    // 권한 및 사용자 정보 로드
    useEffect(() => {
        if (isOpen) {
            loadAuthAndUserInfo();
        }
    }, [isOpen]);

    const loadAuthAndUserInfo = async () => {
        try {
            // 현재 로그인 사용자 정보 가져오기
            const loginStatus = await comms.checkLoginStatus();
            if (loginStatus.Success && loginStatus.IsLoggedIn && loginStatus.User) {
                const userId = loginStatus.User.Id;
                const userLevel = loginStatus.User.Level || 0;
                setCurrentUserId(userId);

                // 업무일지(jobreport) 권한 가져오기
                const authResponse = await comms.checkAuth('jobreport', 5);
                const jobReportAuthLevel = authResponse.EffectiveLevel || 0;

                // 유효 권한 레벨 = Max(사용자레벨, 권한레벨)
                const effectiveLevel = Math.max(userLevel, jobReportAuthLevel);
                setCanViewAll(effectiveLevel >= 5);
            }
        } catch (error) {
            console.error('권한 정보 로드 오류:', error);
            setCanViewAll(false);
        }
    };

    // 데이터 로드
    useEffect(() => {
        if (isOpen && currentUserId) {
            loadData();
        }
    }, [isOpen, currentMonth, currentUserId, canViewAll]);

    const loadData = async () => {
        setLoading(true);
        try {
            // 현재는 기존 API를 사용하여 월별 데이터를 가져옴
            const startDate = `${currentMonth}-01`;
            const year = parseInt(currentMonth.substring(0, 4));
            const month = parseInt(currentMonth.substring(5, 7));
            const lastDay = new Date(year, month, 0).getDate();
            const endDate = `${currentMonth}-${String(lastDay).padStart(2, '0')}`;

            const [jobReportResponse, holidayResponse] = await Promise.all([
                comms.getJobReportList(startDate, endDate, '', ''),
                comms.getHolidayList(currentMonth)
            ]);

            if (jobReportResponse.Success && jobReportResponse.Data) {
                processData(jobReportResponse.Data, holidayResponse.Data || [], lastDay);
            }
        } catch (error) {
            console.error('데이터 로드 오류:', error);
        } finally {
            setLoading(false);
        }
    };

    const processData = (items: any[], holidays: HolidayItem[], lastDay: number) => {
        // 날짜 컬럼 생성
        const columns: DayColumn[] = [];
        const year = parseInt(currentMonth.substring(0, 4));
        const month = parseInt(currentMonth.substring(5, 7));

        for (let day = 1; day <= lastDay; day++) {
            const date = new Date(year, month - 1, day);
            const dayOfWeek = weekDays[date.getDay()];
            const dateStr = `${currentMonth}-${String(day).padStart(2, '0')}`;
            const holiday = holidays.find(h => h.pdate === dateStr);

            columns.push({
                day,
                dayOfWeek,
                isHoliday: holiday?.free || false,
                holidayMemo: holiday?.memo
            });
        }
        setDayColumns(columns);

        // 사용자별 데이터 집계
        const userMap = new Map<string, UserRow>();

        items.forEach(item => {
            const uid = item.id || item.uid;
            const uname = item.name || item.uname || uid;
            const pdate = item.pdate?.substring(0, 10);

            if (!pdate || !pdate.startsWith(currentMonth)) return;

            // 권한 체크: 권한 레벨이 5 미만이고 본인이 아니면 스킵
            if (!canViewAll && uid !== currentUserId) return;

            const day = parseInt(pdate.substring(8, 10));

            if (!userMap.has(uid)) {
                userMap.set(uid, {
                    uid,
                    uname,
                    processs: item.userprocess || item.process || '',
                    dailyData: new Map(),
                    totalHrs: 0,
                    totalOt: 0,
                    totalHolidayOt: 0
                });
            }

            const userRow = userMap.get(uid)!;
            const existing = userRow.dailyData.get(day);
            const hrs = (existing?.hrs || 0) + (item.hrs || 0);
            const ot = (existing?.ot || 0) + (item.ot || 0);
            const jobtype = item.type || existing?.jobtype || '';

            userRow.dailyData.set(day, { hrs, ot, jobtype });
            userRow.totalHrs += item.hrs || 0;

            // 휴일 OT 계산
            const column = columns[day - 1];
            if (column?.isHoliday) {
                userRow.totalHolidayOt += item.ot || 0;
            } else {
                userRow.totalOt += item.ot || 0;
            }
        });

        setUserRows(Array.from(userMap.values()).sort((a, b) => a.uname.localeCompare(b.uname)));
    };

    // 월 변경
    const changeMonth = (delta: number) => {
        const [year, month] = currentMonth.split('-').map(Number);
        const newDate = new Date(year, month - 1 + delta, 1);
        setCurrentMonth(`${newDate.getFullYear()}-${String(newDate.getMonth() + 1).padStart(2, '0')}`);
    };

    // 셀 색상 결정
    const getCellStyle = (data: { hrs: number; ot: number; jobtype: string } | undefined, isHoliday: boolean) => {
        if (!data) return 'text-gray-400';

        if (data.jobtype === '휴가') return 'text-red-500 font-medium';
        if (isHoliday) return 'text-green-500 font-medium';

        if (data.hrs > 8) return 'text-blue-500 font-medium';
        if (data.hrs < 8) return 'text-red-500';
        if (data.ot > 0) return 'text-purple-500 font-medium';

        return 'text-white';
    };

    // 셀 내용 포맷
    const formatCellContent = (data: { hrs: number; ot: number; jobtype: string } | undefined, isHoliday: boolean) => {
        if (!data) return '--';

        if (data.jobtype === '휴가' && data.hrs + data.ot === 8) return '휴가';

        const prefix = isHoliday ? '*' : '';
        return `${prefix}${data.hrs}+${data.ot}`;
    };

    // 엑셀 내보내기 (간단한 CSV)
    const exportToExcel = () => {
        let csv = '사원명,' + dayColumns.map(c => `${c.day}(${c.dayOfWeek})`).join(',') + ',합계\n';

        userRows.forEach(row => {
            const cells = dayColumns.map(col => {
                const data = row.dailyData.get(col.day);
                return formatCellContent(data, col.isHoliday);
            });
            const summary = `${row.totalHrs}+${row.totalOt}(*${row.totalHolidayOt})`;
            csv += `${row.uname},${cells.join(',')},${summary}\n`;
        });

        const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `업무일지_일별집계_${currentMonth}.csv`;
        link.click();
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-gradient-to-br from-gray-900 to-gray-800 rounded-2xl shadow-2xl w-full max-w-7xl max-h-[90vh] flex flex-col">
                {/* 헤더 */}
                <div className="flex items-center justify-between p-6 border-b border-white/10">
                    <div className="flex items-center gap-4">
                        <h2 className="text-2xl font-bold text-white">일별 근무시간 집계</h2>
                        <div className="flex items-center gap-2">
                            <button
                                onClick={() => changeMonth(-1)}
                                className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                            >
                                <ChevronLeft className="w-5 h-5 text-white" />
                            </button>
                            <span className="text-lg font-medium text-white min-w-[100px] text-center">
                                {currentMonth}
                            </span>
                            <button
                                onClick={() => changeMonth(1)}
                                className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                            >
                                <ChevronRight className="w-5 h-5 text-white" />
                            </button>
                        </div>
                    </div>
                    <div className="flex items-center gap-2">
                        <button
                            onClick={exportToExcel}
                            className="px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg transition-colors flex items-center gap-2"
                        >
                            <Download className="w-4 h-4" />
                            내보내기
                        </button>
                        <button
                            onClick={onClose}
                            className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                        >
                            <X className="w-6 h-6 text-white" />
                        </button>
                    </div>
                </div>

                {/* 테이블 */}
                <div className="flex-1 overflow-auto p-6">
                    {loading ? (
                        <div className="flex items-center justify-center h-full">
                            <div className="text-white/50">데이터를 불러오는 중...</div>
                        </div>
                    ) : (
                        <table className="w-full border-collapse">
                            <thead className="sticky top-0 bg-gray-800 z-10">
                                <tr>
                                    <th className="px-3 py-2 text-left text-xs font-medium text-white/70 uppercase border border-white/10 bg-gray-800">
                                        사원명
                                    </th>
                                    {dayColumns.map(col => (
                                        <th
                                            key={col.day}
                                            className={`px-2 py-2 text-center text-xs font-medium uppercase border border-white/10 ${col.isHoliday ? 'bg-green-900/30 text-green-400' :
                                                    col.dayOfWeek === '일' ? 'bg-red-900/30 text-red-400' :
                                                        col.dayOfWeek === '토' ? 'bg-blue-900/30 text-blue-400' :
                                                            'bg-gray-800 text-white/70'
                                                }`}
                                            title={col.holidayMemo}
                                        >
                                            {col.day}<br />({col.dayOfWeek})
                                        </th>
                                    ))}
                                    <th className="px-3 py-2 text-center text-xs font-medium text-white/70 uppercase border border-white/10 bg-gray-800">
                                        합계
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                {userRows.length === 0 ? (
                                    <tr>
                                        <td colSpan={dayColumns.length + 2} className="px-4 py-8 text-center text-white/50">
                                            조회된 데이터가 없습니다.
                                        </td>
                                    </tr>
                                ) : (
                                    userRows.map(row => (
                                        <tr key={row.uid} className="hover:bg-white/5 transition-colors">
                                            <td className="px-3 py-2 text-sm text-white border border-white/10 whitespace-nowrap">
                                                {row.uname}
                                            </td>
                                            {dayColumns.map(col => {
                                                const data = row.dailyData.get(col.day);
                                                return (
                                                    <td
                                                        key={col.day}
                                                        className={`px-2 py-2 text-center text-sm border border-white/10 ${getCellStyle(data, col.isHoliday)}`}
                                                    >
                                                        {formatCellContent(data, col.isHoliday)}
                                                    </td>
                                                );
                                            })}
                                            <td className="px-3 py-2 text-center text-sm text-white border border-white/10 font-medium whitespace-nowrap">
                                                {row.totalHrs.toFixed(1)}+{row.totalOt.toFixed(1)}(*{row.totalHolidayOt.toFixed(1)})
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    )}
                </div>

                {/* 범례 */}
                <div className="px-6 py-4 border-t border-white/10 bg-gray-800/50">
                    <div className="flex flex-wrap gap-4 text-xs text-white/70">
                        <div><span className="text-gray-400">--</span> : 자료없음</div>
                        <div><span className="text-red-500">휴가</span> : 휴가</div>
                        <div><span className="text-green-500">*8+2</span> : 휴일근무</div>
                        <div><span className="text-blue-500">9+0</span> : 8시간 초과</div>
                        <div><span className="text-red-500">7+0</span> : 8시간 미만</div>
                        <div><span className="text-purple-500">8+2</span> : 8시간+OT</div>
                    </div>
                </div>
            </div>
        </div>
    );
}
