// app/schedule/page.tsx

"use client"

import { CalendarRange, Clock, Loader2 } from 'lucide-react';
import Image from 'next/image';
import React, { useEffect, useRef, useState } from 'react';
import { readJsonFile } from '../actions/jsonEditor';
import falconIcon from '../assets/falcon.svg';
import porpoiseIcon from '../assets/porpoise.svg';
import { PageHeader } from '../components/ui/PageHeader';

// --- Helper Functions ---
const parseTimeBlock = (timeStr: string) => {
    if (!timeStr || timeStr === 'Ledig') return null;
    const matches = timeStr.match(/(\d{1,2}):(\d{2})/g);
    if (!matches || matches.length < 2) return null;
    const parse = (t: string) => { const [h, m] = t.split(':').map(Number); return h + (m / 60); };
    return { start: parse(matches[0]), end: parse(matches[1]) };
};

const checkOverlap = (time1?: string, time2?: string) => {
    const t1 = time1 ? parseTimeBlock(time1) : null;
    const t2 = time2 ? parseTimeBlock(time2) : null;
    if (!t1 || !t2) return false;
    return t1.start < t2.end && t1.end > t2.start;
};

// --- Types & Components ---
interface ShiftData { time: string; title?: string; notes?: string; }
interface ShiftBlockProps { team: 'PF' | 'TU'; data: ShiftData; pos: { top: number; height: number }; isOverlapping: boolean; }

const ShiftBlock: React.FC<ShiftBlockProps> = ({ team, data, pos, isOverlapping }) => {
    const isPF = team === 'PF';
    const widthClasses = isOverlapping ? isPF ? "left-1 right-1/2 mr-0.5" : "left-1/2 right-1 ml-0.5" : "left-1 right-1";
    const bgClasses = isPF ? "bg-gradient-to-br from-gold to-goldenrod border-goldenrod" : "bg-gradient-to-br from-seafoam to-slate-teal border-slate-teal";
    const textMain = isPF ? "text-ebony" : "text-eggshell";
    const textMuted = isPF ? "text-ebony/90" : "text-eggshell/90";
    const notesBg = isPF ? "bg-eggshell/30 border-seafoam/5" : "bg-gold/20 border-eggshell/10";
    const fallbackTitle = isPF ? "PF" : "TU";

    const iconSrc = isPF ? falconIcon : porpoiseIcon;

    return (
        <div
            className={`absolute ${widthClasses} ${bgClasses} rounded-lg p-1.5 flex flex-col overflow-hidden shadow-sm border transition-colors hover:brightness-105`}
            style={{ top: `${pos.top}px`, height: `${pos.height}px` }}
        >
            <p className={`text-[10px] font-black ${textMain} uppercase tracking-wide leading-tight truncate flex items-center gap-1`}>
                <Image
                    src={iconSrc}
                    alt={team}
                    width={10}
                    height={10}
                    className={`shrink-0 opacity-90 ${!isPF ? 'brightness-0 invert' : ''}`}
                />
                {data.title || fallbackTitle}
            </p>
            <p className={`text-[9px] font-bold ${textMuted} flex items-center mt-0.5 whitespace-nowrap`}>
                <Clock size={8} className="mr-0.5 shrink-0" />
                <span className="truncate">{data.time}</span>
            </p>
            {data.notes && pos.height > 50 && (
                <div className={`mt-1 ${notesBg} p-1 rounded-md border`}>
                    <p className={`text-[9px] font-medium ${textMain} leading-tight truncate pb-1`}>{data.notes}</p>
                </div>
            )}
        </div>
    );
};

// --- Main Schedule View ---
export default function Schedule() {
    const startHour = 8;
    const endHour = 17;
    const hours = Array.from({ length: endHour - startHour + 1 }, (_, i) => startHour + i);
    const PIXELS_PER_HOUR = 60;
    const GRID_PADDING_TOP = 24;
    const TOTAL_GRID_HEIGHT = (hours.length * PIXELS_PER_HOUR) + GRID_PADDING_TOP;
    const containerRef = useRef<HTMLDivElement>(null);

    const [scheduleData, setScheduleData] = useState<any[]>([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const loadSchedule = async () => {
            if (navigator.onLine) {
                const res = await readJsonFile('schedule.json');
                if (res.success && res.data) {
                    setScheduleData(res.data);
                    localStorage.setItem('kullaberg_schedule_cache', JSON.stringify(res.data));
                }
            } else {
                const cachedData = localStorage.getItem('kullaberg_schedule_cache');
                if (cachedData) setScheduleData(JSON.parse(cachedData));
            }
            setIsLoading(false);
        };
        loadSchedule();
    }, []);

    const calculatePosition = (timeStr: string) => {
        const t = parseTimeBlock(timeStr);
        if (!t) return null;
        const topOffset = (t.start - startHour) * PIXELS_PER_HOUR;
        const duration = (t.end - t.start) * PIXELS_PER_HOUR;
        return { top: topOffset + GRID_PADDING_TOP + 1, height: duration - 2 };
    };

    if (isLoading) return <div className="flex justify-center py-20"><Loader2 className="animate-spin text-slate-teal" size={40} /></div>;

    return (
        <div className="space-y-2 animate-fade-in w-full">
            <PageHeader
                title="Veckoschema"
                icon={CalendarRange}
                description="Här hittar du när vi bemannar Kullaberg."
            />

            <div className="bg-white/40 backdrop-blur-md border border-white/40 rounded-3xl shadow-sm overflow-hidden flex flex-col max-h-[60vh] h-max min-h-125 w-full">
                <div className="flex-1 overflow-auto scrollbar-hide" ref={containerRef}>
                    <div className="flex min-w-200 w-full">
                        <div className="sticky left-0 z-20 w-12 flex-none bg-white/60 backdrop-blur-md border-r border-white/40 shadow-[2px_0_5px_rgba(0,0,0,0.02)]">
                            <div className="sticky top-0 z-30 h-10 border-b border-white/40 bg-white/40 backdrop-blur-md rounded-tl-3xl"></div>
                            <div className="relative w-full" style={{ height: `${TOTAL_GRID_HEIGHT}px` }}>
                                {hours.map((hour, i) => (
                                    <div key={hour} className="absolute w-full flex justify-center" style={{ top: `${i * PIXELS_PER_HOUR + GRID_PADDING_TOP}px` }}>
                                        <span className="text-[10px] font-bold text-slate-teal -mt-2 px-1 rounded ">
                                            {hour.toString().padStart(2, '0')}:00
                                        </span>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div className="flex-auto relative">
                            <div className="sticky top-0 z-10 flex h-10 border-b border-white/40 bg-white/60 backdrop-blur-md">
                                {scheduleData.map((d) => (
                                    <div key={d.day} className="flex-1 flex items-center justify-center border-l border-white/20 first:border-l-0 min-w-25">
                                        <span className="text-xs font-black text-ebony uppercase tracking-widest">{d.day.substring(0, 3)}</span>
                                    </div>
                                ))}
                            </div>

                            <div className="relative w-full" style={{ height: `${TOTAL_GRID_HEIGHT}px` }}>
                                <div className="absolute inset-0 z-0">
                                    {hours.map((hour, i) => (
                                        <div key={hour} className="absolute w-full border-t border-white/30" style={{ top: `${i * PIXELS_PER_HOUR + GRID_PADDING_TOP}px`, height: `${PIXELS_PER_HOUR}px` }} />
                                    ))}
                                </div>
                                <div className="absolute inset-0 flex z-0">
                                    {scheduleData.map((d, colIndex) => {
                                        const pfData = d.pilgrimsfalkarna as ShiftData | undefined;
                                        const tuData = d.tumlarna as ShiftData | undefined;
                                        const hasPF = !!(pfData && pfData.time && pfData.time !== 'Ledig');
                                        const hasTU = !!(tuData && tuData.time && tuData.time !== 'Ledig');
                                        const isOverlapping = hasPF && hasTU && checkOverlap(pfData.time, tuData.time);

                                        return (
                                            <div key={colIndex} className="flex-1 border-l border-white/30 relative min-w-25">
                                                {hasPF && (() => {
                                                    const pos = calculatePosition(pfData.time);
                                                    return pos ? <ShiftBlock team="PF" data={pfData} pos={pos} isOverlapping={isOverlapping} /> : null;
                                                })()}
                                                {hasTU && (() => {
                                                    const pos = calculatePosition(tuData.time);
                                                    return pos ? <ShiftBlock team="TU" data={tuData} pos={pos} isOverlapping={isOverlapping} /> : null;
                                                })()}
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="flex items-center justify-center space-x-6 py-2 text-xs font-bold text-ebony">
                <span className="flex items-center">
                    <div className="w-6 h-6 bg-linear-to-br from-gold to-goldenrod rounded-lg mr-2 shadow-sm flex items-center justify-center">
                        <Image src={falconIcon} alt="PF" width={14} height={14} />
                    </div>
                    Pilgrimsfalkarna
                </span>
                <span className="flex items-center">
                    <div className="w-6 h-6 bg-linear-to-br from-seafoam to-slate-teal rounded-lg mr-2 shadow-sm flex items-center justify-center">
                        <Image src={porpoiseIcon} alt="TU" width={14} height={14} className="brightness-0 invert" />
                    </div>
                    Tumlarna
                </span>
            </div>
        </div>
    );
}