import { useState, useEffect } from 'react';
import { X, ChevronLeft, ChevronRight, Download, Calendar, Users, Clock } from 'lucide-react';
import { clsx } from 'clsx';
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-white/20';

        if (data.jobtype === '휴가') return 'text-danger-400 font-black bg-danger-500/10';
        if (isHoliday) return 'text-success-400 font-bold bg-success-500/10 underline underline-offset-4';

        if (data.hrs > 8) return 'text-primary-400 font-bold underline underline-offset-2';
        if (data.hrs < 8) return 'text-danger-500 font-medium';
        if (data.ot > 0) return 'text-warning-400 font-bold italic';

        return 'text-white/70';
    };

    // 셀 내용 포맷
    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: DayColumn) => `${c.day}(${c.dayOfWeek})`).join(',') + ',합계\n';

        userRows.forEach((row: UserRow) => {
            const cells = dayColumns.map((col: DayColumn) => {
                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 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-fade-in" onClick={onClose}>
            <div
                className="glass-effect rounded-3xl w-full max-w-7xl max-h-[95vh] overflow-hidden flex flex-col shadow-2xl border border-white/10 animate-scale-in"
                onClick={(e) => e.stopPropagation()}
            >
                {/* 헤더 */}
                <div className="px-8 py-6 border-b border-white/10 flex items-center justify-between bg-white/5">
                    <div className="flex items-center gap-6">
                        <div className="flex items-center gap-4">
                            <div className="p-2.5 bg-primary-500/20 rounded-xl">
                                <Clock className="w-6 h-6 text-primary-400" />
                            </div>
                            <div>
                                <h2 className="text-xl font-bold text-white leading-tight">일별 근무시간 집계</h2>
                                <p className="text-xs text-white/40 uppercase tracking-widest font-medium mt-0.5">Daily Working Hours Summary</p>
                            </div>
                        </div>

                        {/* 월 선택 UI */}
                        <div className="flex items-center gap-1 bg-white/5 p-1 rounded-xl border border-white/10">
                            <button
                                onClick={() => changeMonth(-1)}
                                className="p-2 hover:bg-white/10 rounded-lg text-white/50 hover:text-white transition-all active:scale-95"
                                title="이전 달"
                            >
                                <ChevronLeft className="w-5 h-5" />
                            </button>
                            <div className="px-4 flex items-center gap-2">
                                <Calendar className="w-4 h-4 text-primary-400" />
                                <span className="text-sm font-bold text-white font-mono min-w-[80px] text-center italic tracking-wider">
                                    {currentMonth}
                                </span>
                            </div>
                            <button
                                onClick={() => changeMonth(1)}
                                className="p-2 hover:bg-white/10 rounded-lg text-white/50 hover:text-white transition-all active:scale-95"
                                title="다음 달"
                            >
                                <ChevronRight className="w-5 h-5" />
                            </button>
                        </div>
                    </div>

                    <div className="flex items-center gap-3">
                        <button
                            onClick={exportToExcel}
                            className="px-5 py-2.5 bg-green-500 hover:bg-green-600 text-white border border-green-500/20 rounded-xl transition-all font-bold flex items-center gap-2 shadow-lg shadow-green-500/20 active:scale-95"
                        >
                            <Download className="w-4 h-4" />
                            <span>CSV 내보내기</span>
                        </button>
                        <button
                            onClick={onClose}
                            className="p-2.5 text-white/30 hover:text-white hover:bg-white/10 rounded-xl transition-all"
                        >
                            <X className="w-6 h-6" />
                        </button>
                    </div>
                </div>

                {/* 테이블 컨텐츠 */}
                <div className="flex-1 overflow-hidden flex flex-col p-6 bg-white/[0.02]">
                    <div className="flex-1 glass-effect rounded-2xl border border-white/10 flex flex-col overflow-hidden shadow-2xl">
                        {loading ? (
                            <div className="flex-1 flex flex-col items-center justify-center">
                                <RefreshCw className="w-12 h-12 text-primary-500/30 animate-spin mb-4" />
                                <p className="text-white/40 font-medium">데이터를 분석하고 집계하는 중...</p>
                            </div>
                        ) : (
                            <div className="flex-1 overflow-auto custom-scrollbar">
                                <table className="w-full border-separate border-spacing-0">
                                    <thead className="sticky top-0 z-20">
                                        <tr>
                                            <th className="px-6 py-4 text-left text-xs font-bold text-white/70 uppercase tracking-widest bg-gray-900 border-b border-r border-white/10 sticky left-0 z-30">
                                                사원명
                                            </th>
                                            {dayColumns.map(col => (
                                                <th
                                                    key={col.day}
                                                    className={clsx(
                                                        "px-2 py-3 text-center text-[10px] font-black uppercase tracking-tighter border-b border-r border-white/5 bg-gray-900/95 backdrop-blur-sm min-w-[50px]",
                                                        col.isHoliday ? 'text-danger-400 bg-danger-500/10' :
                                                            col.dayOfWeek === '일' ? 'text-danger-400' :
                                                                col.dayOfWeek === '토' ? 'text-primary-400' :
                                                                    'text-white/40'
                                                    )}
                                                    title={col.holidayMemo}
                                                >
                                                    <div className="flex flex-col items-center">
                                                        <span className="text-sm font-mono leading-none">{col.day}</span>
                                                        <span className="mt-1 opacity-60 leading-none">{col.dayOfWeek}</span>
                                                    </div>
                                                </th>
                                            ))}
                                            <th className="px-4 py-4 text-center text-xs font-bold text-primary-400 uppercase tracking-widest bg-gray-900 border-b border-white/10 sticky right-0 z-30 shadow-[-4px_0_12px_rgba(0,0,0,0.5)]">
                                                통계 (Hr + OT)
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-white/[0.03]">
                                        {userRows.length === 0 ? (
                                            <tr>
                                                <td colSpan={dayColumns.length + 2} className="px-4 py-32 text-center">
                                                    <Users className="w-20 h-20 text-white/5 mx-auto mb-4" />
                                                    <p className="text-white/20 font-medium">조회된 데이터가 없습니다.</p>
                                                </td>
                                            </tr>
                                        ) : (
                                            userRows.map((row: UserRow) => (
                                                <tr key={row.uid} className="hover:bg-white/[0.03] transition-colors group">
                                                    <td className="px-6 py-2.5 text-sm font-bold text-white bg-gray-900/50 border-r border-white/10 sticky left-0 z-10 backdrop-blur-md group-hover:bg-primary-500/10 transition-colors">
                                                        {row.uname}
                                                    </td>
                                                    {dayColumns.map((col: DayColumn) => {
                                                        const data = row.dailyData.get(col.day);
                                                        return (
                                                            <td
                                                                key={col.day}
                                                                className={clsx(
                                                                    "px-2 py-2 text-center text-xs border-r border-white/[0.02] last:border-r-0",
                                                                    getCellStyle(data, col.isHoliday)
                                                                )}
                                                            >
                                                                <span className="font-mono font-medium tracking-tighter italic opacity-90">
                                                                    {formatCellContent(data, col.isHoliday)}
                                                                </span>
                                                            </td>
                                                        );
                                                    })}
                                                    <td className="px-4 py-2.5 text-center bg-gray-900/50 border-l border-white/10 sticky right-0 z-10 backdrop-blur-md shadow-[-4px_0_12px_rgba(0,0,0,0.5)] group-hover:bg-primary-500/10 transition-colors">
                                                        <div className="flex items-center justify-center gap-1.5 font-mono text-xs font-bold">
                                                            <span className="text-white tracking-widest">{row.totalHrs.toFixed(1)}</span>
                                                            <span className="text-white/20 italic">+</span>
                                                            <span className="text-primary-400 tracking-widest">{row.totalOt.toFixed(1)}</span>
                                                            {row.totalHolidayOt > 0 && (
                                                                <span className="text-warning-400 ml-1 text-[10px] bg-warning-500/10 px-1 rounded">
                                                                    *{row.totalHolidayOt.toFixed(1)}
                                                                </span>
                                                            )}
                                                        </div>
                                                    </td>
                                                </tr>
                                            ))
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </div>
                </div>

                {/* 하단 범례 (Legend) */}
                <div className="px-8 py-4 border-t border-white/10 bg-white/5 flex items-center gap-6 overflow-x-auto custom-scrollbar no-scrollbar">
                    <span className="text-[10px] font-black text-white/30 uppercase tracking-[0.2em] shrink-0 border-r border-white/10 pr-6 mr-2">Legend</span>
                    <div className="flex items-center gap-6 text-[11px] font-bold whitespace-nowrap">
                        <div className="flex items-center gap-2">
                            <span className="w-5 h-5 rounded-md bg-white/5 flex items-center justify-center text-gray-500 font-mono italic">--</span>
                            <span className="text-white/40">기록 없음</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <span className="px-2 py-0.5 rounded-md bg-danger-500/20 text-danger-400 font-bold">휴가</span>
                            <span className="text-white/40">연차/반차</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <span className="px-2 py-0.5 rounded-md bg-success-500/20 text-success-400 font-mono font-bold">*8+4</span>
                            <span className="text-white/40">휴일 근무</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <span className="px-2 py-0.5 rounded-md bg-primary-500/20 text-primary-400 font-mono font-bold underline">10+0</span>
                            <span className="text-white/40">기본 초과</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <span className="px-2 py-0.5 rounded-md bg-danger-500/10 text-danger-500 font-mono font-bold">6+0</span>
                            <span className="text-white/40">기본 미달</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <span className="px-2 py-0.5 rounded-md bg-warning-500/20 text-warning-400 font-mono font-bold italic">8+2</span>
                            <span className="text-white/40">OT 발생</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

const RefreshCw = ({ className }: { className?: string }) => (
    <svg
        xmlns="http://www.w3.org/2000/svg"
        width="24" height="24"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        className={className}
    >
        <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" />
        <path d="M21 3v5h-5" />
        <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" />
        <path d="M3 21v-5h5" />
    </svg>
);
