// app/admin/LogTab.tsx
"use client";

import { NotebookText, CalendarRange, CheckCircle, ChevronLeft, ChevronRight, Save, AlertTriangle, FileText, Download } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { type Period, toIsoDate } from './adminTypes';

interface Props {
    periods: Period[];
    dailyLogs: Record<string, string>;
    setDailyLog: (date: string, content: string) => void;
    activePeriodId: string;
    setActivePeriodId: (id: string) => void;
    scheduleData: any[];
}

const getDaysInPeriod = (start: string, end: string) => {
    const days = []; let curr = new Date(start + 'T12:00:00'); const endDate = new Date(end + 'T12:00:00');
    while (curr <= endDate) { days.push(toIsoDate(curr)); curr.setDate(curr.getDate() + 1); }
    return days;
};

export const LogTab: React.FC<Props> = ({ periods, dailyLogs, setDailyLog, activePeriodId, setActivePeriodId, scheduleData }) => {
    const activePeriod = periods.find(p => p.id === activePeriodId);

    const [currentDate, setCurrentDate] = useState<string>(() => {
        const today = toIsoDate(new Date());
        if (activePeriod && today >= activePeriod.startDate && today <= activePeriod.endDate) return today;
        return activePeriod ? activePeriod.startDate : today;
    });

    const [currentText, setCurrentText] = useState("");
    const [saveStatus, setSaveStatus] = useState<'idle' | 'saved'>('idle');

    useEffect(() => {
        setCurrentText(dailyLogs[currentDate] || "");
        setSaveStatus('idle');
    }, [currentDate]);

    useEffect(() => {
        if (saveStatus === 'idle' && currentText === (dailyLogs[currentDate] || "")) {
            setCurrentText(dailyLogs[currentDate] || "");
        }
    }, [dailyLogs, currentDate]);

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

    const handleSave = () => {
        setDailyLog(currentDate, currentText);
        setSaveStatus('saved');
        setTimeout(() => setSaveStatus('idle'), 2000);
    };

    const changeDate = (days: number) => {
        const newDateObj = new Date(currentDate + 'T12:00:00'); newDateObj.setDate(newDateObj.getDate() + days);
        const startObj = new Date(activePeriod.startDate + 'T12:00:00'); const endObj = new Date(activePeriod.endDate + 'T12:00:00');
        if (newDateObj >= startObj && newDateObj <= endObj) setCurrentDate(toIsoDate(newDateObj));
    };

    const dayNameStr = new Date(currentDate + 'T12:00:00').toLocaleDateString('sv-SE', { weekday: 'long' });
    const timelineDays = getDaysInPeriod(activePeriod.startDate, activePeriod.endDate);
    const todayIso = toIsoDate(new Date());

    const exportToCsv = () => {
        if (!activePeriod) return;
        let csvContent = "Datum;Logg\n";
        const sortedDays = Object.keys(dailyLogs).sort((a, b) => a.localeCompare(b));
        sortedDays.forEach(date => {
            if (date >= activePeriod.startDate && date <= activePeriod.endDate) {
                const logContent = dailyLogs[date] || "";
                const cleanContent = logContent
                    .replace(/\n/g, " ")
                    .replace(/;/g, ",")
                    .replace(/"/g, '""');

                csvContent += `${date};"${cleanContent}"\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", `Logg_${activePeriod.name.replace(/ /g, '_')}.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    return (
        <div className="space-y-6 animate-fade-in">
            {/* Datumskrollare likt AttendanceTab */}
            <div className="rounded-3xl shadow-sm transition-all duration-300 bg-white/40 backdrop-blur-md border border-white/40 p-3 sm:p-5 hover:shadow-md">
                <div className="flex justify-between items-center mb-3">
                    <h2 className="text-sm font-black text-ebony uppercase tracking-widest flex items-center mb-2">
                        <CalendarRange className="mr-2 text-slate-teal" size={20} /> Journalöversikt
                    </h2>
                    <select value={activePeriodId} onChange={(e) => setActivePeriodId(e.target.value)} className="bg-white border border-slate-teal/10 py-1.5 px-3 rounded-xl font-bold text-slate-teal text-xs cursor-pointer focus:outline-none shadow-sm">
                        {periods.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                    </select>
                </div>
                <div className="flex overflow-x-auto gap-2.5 pb-3 pt-1 px-2 scrollbar-hide">
                    {timelineDays.map(day => {
                        const dayName = new Date(day + 'T12:00:00').toLocaleDateString('sv-SE', { weekday: 'long' }).toLowerCase();
                        const daySchedule = scheduleData.find(d => d.day.toLowerCase() === dayName);
                        const hasWork = daySchedule && ((daySchedule.pilgrimsfalkarna?.time && daySchedule.pilgrimsfalkarna.time !== 'Ledig') || (daySchedule.tumlarna?.time && daySchedule.tumlarna.time !== 'Ledig'));

                        const hasLog = !!dailyLogs[day] && dailyLogs[day].trim() !== "";
                        const isSelected = day === currentDate;

                        let bgClass = "bg-white text-ebony border-slate-teal/10";
                        if (!hasWork) bgClass = "bg-slate-teal/5 text-ebony/40 border-transparent";
                        else if (hasLog) bgClass = "bg-moss text-white border-moss shadow-inner";
                        else if (day <= todayIso) bgClass = "bg-goldenrod text-white border-goldenrod shadow-inner";

                        return (
                            <button key={day} onClick={() => setCurrentDate(day)} className={`flex flex-col items-center justify-center min-w-14 p-2 rounded-xl border transition-colors ${bgClass} ${isSelected ? 'ring-2 ring-slate-teal ring-offset-2 ring-offset-eggshell' : 'hover:brightness-95 shadow-sm'}`}>
                                <span className="text-[10px] font-black uppercase tracking-wider">{new Date(day + 'T12:00:00').toLocaleDateString('sv-SE', { weekday: 'short' })}</span>
                                <span className="text-sm font-black">{new Date(day + 'T12:00:00').getDate()}/{new Date(day + 'T12:00:00').getMonth() + 1}</span>
                            </button>
                        );
                    })}
                </div>
            </div>

            <div className="flex flex-row justify-between items-center rounded-3xl shadow-sm transition-all duration-300 bg-white/40 backdrop-blur-md border border-white/40 p-3 sm:p-5 hover:shadow-md gap-4">
                <button onClick={() => changeDate(-1)} className="p-3 text-slate-teal bg-slate-teal/10 hover:bg-slate-teal/30 rounded-2xl transition-colors"><ChevronLeft size={24} /></button>
                <div className="text-center flex-1">
                    <h2 className="text-lg font-black text-ebony capitalize mb-0.5">{dayNameStr}</h2>
                    <p className="text-[11px] font-black uppercase tracking-widest text-moss">{currentDate}</p>
                </div>
                <button onClick={() => changeDate(1)} className="p-3 text-slate-teal bg-slate-teal/10 hover:bg-slate-teal/30 rounded-2xl transition-colors"><ChevronRight size={24} /></button>
            </div>

            {/* Skrivyta */}
            <div className="rounded-3xl shadow-sm transition-all duration-300 bg-white/40 backdrop-blur-md border border-white/40 p-3 sm:p-5 hover:shadow-md">
                <h2 className="text-xl font-black text-ebony uppercase tracking-widest flex items-center mb-6">
                    <div className="bg-white p-2.5 rounded-xl mr-3 text-slate-teal shadow-sm">
                        <NotebookText size={24} />
                    </div>
                    Daglig Journal
                </h2>

                <textarea
                    value={currentText}
                    onChange={(e) => setCurrentText(e.target.value)}
                    placeholder="Vad har hänt idag? Något trasigt staket? Spännande djurobservation? Sur turist?"
                    className="w-full h-48 bg-white border border-slate-teal/10 p-4 rounded-2xl text-sm font-medium resize-none focus:outline-none focus:border-slate-teal shadow-sm mb-6"
                />

                <div className="flex items-center justify-between">
                    <div>
                        {saveStatus === 'saved' && <span className="text-xs font-bold text-moss flex items-center"><CheckCircle size={14} className="mr-1" /> Sparat!</span>}
                        {dailyLogs[currentDate] && currentText !== dailyLogs[currentDate] && <span className="text-xs font-bold text-goldenrod flex items-center"><AlertTriangle size={14} className="mr-1" /> Osparade ändringar</span>}
                    </div>
                    <button
                        onClick={handleSave}
                        className="bg-slate-teal text-eggshell font-black uppercase tracking-widest text-xs px-6 py-3 rounded-xl hover:bg-ebony transition-colors shadow-sm flex items-center gap-2"
                    >
                        <Save size={16} /> Spara
                    </button>
                </div>
            </div>


            <div className="flex flex-row justify-center items-center p-3 sm:p-5">
                <button onClick={exportToCsv} className="flex items-center justify-center gap-2 bg-seafoam text-eggshell font-black uppercase tracking-widest text-[10px] px-5 py-3 rounded-xl hover:bg-slate-teal transition-colors shadow-sm">
                    <Download size={16} /> Exportera Journal till Excel
                </button>
            </div>
        </div>
    );
};