// app/admin/ReportTab.tsx

"use client";

import { AlertTriangle, ChevronDown, ChevronUp, Clock, Download, Users } from 'lucide-react';
import Image from 'next/image';
import React, { useState } from 'react';
import scheduleData from '../data/schedule.json';
import falconIcon from '../assets/falcon.svg';
import porpoiseIcon from '../assets/porpoise.svg';
import { type AttendanceDataMap, formatTimeHHMM, isWeekend, type Period, type Role } from './adminTypes';
import { getTeamShiftInfo } from './AttendanceTab';

interface Props {
    periods: Period[];
    attendance: AttendanceDataMap;
    activePeriodId: string;
    setActivePeriodId: (id: string) => void;
    currentUserRole: Role;
}

const POT_HOUR_LIMIT = 90;
const formatHours = (h: number) => Number(h.toFixed(1)).toString();

export const ReportTab: React.FC<Props> = ({ periods, attendance, activePeriodId, setActivePeriodId, currentUserRole }) => {
    const activePeriod = periods.find(p => p.id === activePeriodId);
    const [expandedYouthId, setExpandedYouthId] = useState<string | null>(null);

    if (!activePeriod) return <p className="text-center font-bold text-slate-teal mt-10">Ingen period tillgänglig.</p>;

    const getPeriodHoursTotal = (youthId: string): number => {
        let total = 0;
        for (const key in attendance) {
            const entry = attendance[key];
            if (entry.youthId === youthId && entry.date >= activePeriod.startDate && entry.date <= activePeriod.endDate) {
                total += entry.weightedHours;
            }
        }
        return total;
    };

    const getTimelineForYouth = (youthId: string) => {
        return Object.values(attendance)
            .filter(a => a.youthId === youthId && a.date >= activePeriod.startDate && a.date <= activePeriod.endDate)
            .sort((a, b) => {
                if (a.date !== b.date) return a.date.localeCompare(b.date);
                return a.shiftId === 'MORNING' ? -1 : 1;
            });
    };

    const exportToCSV = () => {
        if (!activePeriod) return;

        let csvContent = "Datum;Pass;Namn;Lag;Status;Arbetad Tid (HH:MM);Viktad Pott;Anteckning\n";
        const entries = Object.values(attendance).filter(a => a.date >= activePeriod.startDate && a.date <= activePeriod.endDate);

        entries.sort((a, b) => {
            if (a.date !== b.date) return a.date.localeCompare(b.date);
            if (a.shiftId !== b.shiftId) return a.shiftId.localeCompare(b.shiftId);
            const nameA = activePeriod.youthList.find(y => y.id === a.youthId)?.name || '';
            const nameB = activePeriod.youthList.find(y => y.id === b.youthId)?.name || '';
            return nameA.localeCompare(nameB);
        });

        entries.forEach(entry => {
            const youth = activePeriod.youthList.find(y => y.id === entry.youthId);
            if (!youth) return;

            const isWknd = isWeekend(entry.date);
            const shift = isWknd ? 'Hela dagen' : (entry.shiftId === 'MORNING' ? 'Morgon' : 'Eftermiddag');

            const teamName = youth.team === 'PF' ? 'Pilgrimsfalk' : 'Tumlare';
            const worked = formatTimeHHMM(entry.hoursWorked);
            const weighted = entry.weightedHours.toFixed(2).replace('.', ',');
            const note = entry.note || '';

            csvContent += `${entry.date};${shift};${youth.name};${teamName};${entry.status};${worked};${weighted};${note}\n`;
        });

        csvContent += "\nSummering (Timpott)\nNamn;Lag;Total Viktad Pott\n";

        const sortedYouth = [...activePeriod.youthList].sort((a, b) => a.name.localeCompare(b.name));

        sortedYouth.forEach(youth => {
            const total = getPeriodHoursTotal(youth.id).toFixed(2).replace('.', ',');
            const teamName = youth.team === 'PF' ? 'Pilgrimsfalk' : 'Tumlare';
            csvContent += `${youth.name};${teamName};${total}\n`;
        });

        const blob = new Blob(["\uFEFF" + csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.setAttribute("href", url);
        link.setAttribute("download", `Narvaro_${activePeriod.name.replace(/ /g, '_')}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    const sortedActiveYouth = [...activePeriod.youthList].sort((a, b) => a.name.localeCompare(b.name));

    return (
        <div className="space-y-6 animate-fade-in">
            {/* Header / Period Selector */}
            <div className="bg-eggshell border-2 border-slate-teal/20 p-4 md:p-6 rounded-2xl shadow-sm text-center flex flex-col md:flex-row justify-between items-center gap-4">
                <select
                    value={activePeriodId}
                    onChange={(e) => { setActivePeriodId(e.target.value); setExpandedYouthId(null); }}
                    className="bg-white border border-slate-teal/20 p-2.5 rounded-lg font-bold text-slate-teal w-full md:w-auto focus:outline-none"
                >
                    {periods.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
                <div>
                    <h2 className="text-xl font-black text-ebony uppercase tracking-widest">{activePeriod.name}</h2>
                    <p className="font-bold text-moss">{activePeriod.startDate} — {activePeriod.endDate}</p>
                </div>
            </div>

            {/* PERIOD HOUR POT REPORT */}
            <div className="bg-eggshell border-2 border-slate-teal/20 p-4 md:p-6 rounded-2xl shadow-sm">
                <div className="flex flex-col md:flex-row justify-between md:items-center mb-8 gap-4 px-1 md:px-2">
                    <h2 className="text-xl font-black text-ebony uppercase tracking-widest flex items-center">
                        <Users className="mr-3 text-slate-teal" size={24} />
                        Timrapport
                    </h2>

                    {currentUserRole !== 'Viewer' && (
                        <button
                            onClick={exportToCSV}
                            className="flex items-center justify-center gap-2 bg-seafoam/20 hover:bg-seafoam/40 text-slate-teal font-bold px-5 py-2.5 rounded-lg transition-colors border border-seafoam/30 w-full md:w-auto"
                        >
                            <Download size={18} />
                            Exportera till Excel
                        </button>
                    )}
                </div>

                <div className="space-y-4">
                    {sortedActiveYouth.map(youth => {
                        const total = getPeriodHoursTotal(youth.id);
                        const warningStatus: 'none' | 'yellow' | 'red' = total > POT_HOUR_LIMIT ? 'red' : (total >= POT_HOUR_LIMIT - 10 ? 'yellow' : 'none');
                        const isExpanded = expandedYouthId === youth.id;
                        const timeline = getTimelineForYouth(youth.id);

                        return (
                            <div key={youth.id} className="bg-white border border-slate-teal/10 rounded-xl shadow-inner overflow-hidden">
                                <div className="flex flex-col md:flex-row md:justify-between md:items-center p-6 md:px-8 gap-6">
                                    <div className="flex flex-col gap-2">
                                        <div className="flex items-center gap-3">
                                            <div className={`flex items-center justify-center w-8 h-8 rounded-full ${youth.team === 'PF' ? 'bg-gold' : 'bg-seafoam'} shrink-0 shadow-sm`}>
                                                <Image
                                                    src={youth.team === 'PF' ? falconIcon : porpoiseIcon}
                                                    alt={youth.team === 'PF' ? 'Pilgrimsfalk' : 'Tumlare'}
                                                    width={18}
                                                    height={18}
                                                />
                                            </div>
                                            <span className="font-bold text-ebony text-xl">{youth.name}</span>
                                        </div>
                                        <button
                                            onClick={() => setExpandedYouthId(isExpanded ? null : youth.id)}
                                            className="flex items-center text-xs font-bold text-slate-teal hover:text-ebony transition-colors w-fit bg-slate-teal/5 px-2.5 py-1.5 rounded mt-1"
                                        >
                                            {isExpanded ? <ChevronUp size={14} className="mr-1" /> : <ChevronDown size={14} className="mr-1" />}
                                            {isExpanded ? 'Dölj detaljer' : 'Visa detaljer'}
                                        </button>
                                    </div>

                                    <div className="flex items-center justify-end gap-5 w-full md:w-auto">
                                        {warningStatus === 'red' && <AlertTriangle className="text-goldenrod shrink-0" size={32} />}
                                        <div className="text-right min-w-30 md:min-w-37.5">
                                            <div className={`text-3xl md:text-4xl font-black tracking-tight ${warningStatus === 'red' ? 'text-goldenrod' : (warningStatus === 'yellow' ? 'text-goldenrod/80' : 'text-slate-teal')}`}>
                                                {formatHours(total)}<span className="text-lg font-bold text-ebony/60"> / {POT_HOUR_LIMIT}t</span>
                                            </div>
                                            <p className="text-[11px] font-bold text-ebony/60 uppercase tracking-widest mt-1 pr-1">Viktade timmar</p>
                                        </div>
                                    </div>
                                </div>

                                {isExpanded && (
                                    <div className="bg-slate-teal/5 border-t border-slate-teal/10 p-5 md:p-6">
                                        <h4 className="text-sm font-black text-ebony uppercase tracking-widest mb-4 flex items-center">
                                            <Clock size={16} className="mr-2 text-slate-teal" /> Arbetspass & Frånvaro
                                        </h4>
                                        {timeline.length === 0 ? (
                                            <p className="text-sm font-bold text-slate-teal/60 italic">Ingen närvaro loggad ännu.</p>
                                        ) : (
                                            <div className="space-y-2">
                                                {timeline.map((entry, idx) => {
                                                    const isWknd = isWeekend(entry.date);

                                                    // Grab schedule for this exact day to check for 'Extra' shifts accurately!
                                                    const dayNameStr = new Date(entry.date + 'T12:00:00').toLocaleDateString('sv-SE', { weekday: 'long' }).toLowerCase();
                                                    const daySchedule = scheduleData.find(d => d.day.toLowerCase() === dayNameStr);

                                                    let isExtra = false;
                                                    if (!isWknd && daySchedule) {
                                                        const expectedShiftId = getTeamShiftInfo(daySchedule, youth.team).shiftId;
                                                        isExtra = entry.shiftId !== expectedShiftId;
                                                    }

                                                    // Correct display logic: "Hela dagen" for weekends
                                                    const shiftLabel = isWknd ? 'Hela dagen' : (entry.shiftId === 'MORNING' ? 'Morgon' : 'Eftermiddag');

                                                    return (
                                                        <div key={idx} className="flex flex-col sm:flex-row sm:justify-between sm:items-center bg-white border border-slate-teal/10 p-3 rounded-lg text-sm">
                                                            <div className="flex items-center flex-wrap gap-2 mb-2 sm:mb-0">
                                                                <span className="font-bold text-ebony min-w-25">{entry.date}</span>

                                                                <span className="text-xs font-bold text-slate-teal bg-slate-teal/10 px-2 py-0.5 rounded">
                                                                    {shiftLabel}
                                                                </span>

                                                                {isExtra && (
                                                                    <span className="text-[10px] font-bold text-slate-teal bg-slate-teal/10 px-1.5 py-0.5 rounded uppercase tracking-wider">
                                                                        Extra pass
                                                                    </span>
                                                                )}

                                                                {isWknd && <span className="text-xs font-bold text-goldenrod bg-goldenrod/10 px-2 py-0.5 rounded border border-goldenrod/20">Helg</span>}
                                                            </div>

                                                            <div className="flex items-center gap-4">
                                                                {entry.status === 'Pending' ? (
                                                                    <span className="font-bold text-goldenrod bg-goldenrod/10 px-2 py-0.5 rounded">Väntar på registrering</span>
                                                                ) : entry.status === 'Absent' ? (
                                                                    <span className="font-bold text-goldenrod bg-goldenrod/10 px-2 py-0.5 rounded">{entry.note || 'Frånvarande'}</span>
                                                                ) : (
                                                                    <span className="font-bold text-moss bg-moss/10 px-2 py-0.5 rounded">{entry.status === 'Late' ? 'Manuell tid' : 'Närvarande'}</span>
                                                                )}

                                                                <div className="text-right min-w-37.5">
                                                                    <span className="font-bold text-ebony">{formatTimeHHMM(entry.hoursWorked)} arbetat</span>
                                                                    <span className="text-slate-teal font-black ml-2">→ +{entry.weightedHours.toFixed(1)} pott</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        )}
                                    </div>
                                )}
                            </div>
                        );
                    })}
                    {activePeriod.youthList.length === 0 && (
                        <p className="text-sm font-bold text-slate-teal/60 italic text-center">Inga ungdomar i denna period.</p>
                    )}
                </div>
            </div>
        </div>
    );
};