// app/admin/TeamAttendanceCard.tsx

"use client";

import { ClockFading, Zap } from 'lucide-react';
import Image from 'next/image';
import React from 'react';
import falconIcon from '../assets/falcon.svg';
import porpoiseIcon from '../assets/porpoise.svg';
import { formatTimeHHMM, getAttendanceKey, calculateShiftDuration, isWeekend, type AttendanceDataMap, type Youth } from './adminTypes';
import { YouthAttendanceRow } from './YouthAttendanceRow';

interface TeamAttendanceCardProps {
    team: 'PF' | 'TU';
    currentDate: string;
    shiftId: 'MORNING' | 'AFTERNOON';
    standardTime: string;
    periodYouthList: Youth[];
    attendance: AttendanceDataMap;
    setManualAttendance: (date: string, youthId: string, shiftId: 'MORNING' | 'AFTERNOON', status: 'Absent' | 'Late' | 'Present', hours: number, note?: string) => void;
    bulkSetManualAttendance: (records: any[]) => void;
    addPendingAttendance: (date: string, youthId: string, shiftId: 'MORNING' | 'AFTERNOON') => void;
    removeAttendanceEntry: (date: string, youthId: string, shiftId: 'MORNING' | 'AFTERNOON') => void;
}

export const TeamAttendanceCard: React.FC<TeamAttendanceCardProps> = ({
    team,
    currentDate,
    shiftId,
    standardTime,
    periodYouthList,
    attendance,
    setManualAttendance,
    bulkSetManualAttendance,
    addPendingAttendance,
    removeAttendanceEntry
}) => {
    // Logic moved inside the component
    const rawDuration = calculateShiftDuration(standardTime);
    const isWknd = isWeekend(currentDate);
    const actualDuration = isWknd ? Math.max(0, rawDuration - 0.5) : rawDuration;
    const weightedDuration = actualDuration * (isWknd ? 1.5 : 1.0);

    const scheduledYouth = periodYouthList.filter(y => y.team === team);
    const extraYouth = periodYouthList.filter(y => y.team !== team && attendance[getAttendanceKey(currentDate, y.id, shiftId)]);
    const displayYouth = [...scheduledYouth, ...extraYouth].sort((a, b) => a.name.localeCompare(b.name));
    const availableExtras = periodYouthList.filter(y => !displayYouth.some(dy => dy.id === y.id)).sort((a, b) => a.name.localeCompare(b.name));

    const handleQuickLogAll = () => {
        const recordsToUpdate: any[] = [];
        displayYouth.forEach(y => {
            const entry = attendance[getAttendanceKey(currentDate, y.id, shiftId)];
            if (!entry || entry.status === 'Pending') {
                recordsToUpdate.push({ date: currentDate, youthId: y.id, shiftId, status: 'Present', hoursWorked: actualDuration, weightedHours: weightedDuration, note: '' });
            }
        });
        if (recordsToUpdate.length > 0) bulkSetManualAttendance(recordsToUpdate);
    };

    const handleMarkStandard = (youthId: string) => {
        if (actualDuration > 0) setManualAttendance(currentDate, youthId, shiftId, 'Present', actualDuration);
    };

    return (
        <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 flex-wrap justify-between items-center mb-4 gap-3">
                <div className="flex items-center">
                    <div className={`flex items-center justify-center w-10 h-10 rounded-xl ${team === 'PF' ? 'bg-gold' : 'bg-seafoam'} mr-3 shadow-inner shrink-0`}>
                        <Image src={team === 'PF' ? falconIcon : porpoiseIcon} alt={team === 'PF' ? 'Pilgrimsfalk' : 'Tumlare'} width={18} height={18} />
                    </div>
                    <h2 className="text-base font-black text-ebony uppercase tracking-widest">{team === 'PF' ? 'Pilgrimsfalkarna' : 'Tumlarna'}</h2>
                </div>
                <div className="flex items-center gap-3 sm:w-fit w-full justify-between">
                    <div className="flex items-center gap-2 bg-white px-3 py-1.5 rounded-xl border border-slate-teal/5 text-xs text-ebony font-bold shadow-sm">
                        <ClockFading size={14} className="text-slate-teal" /> {standardTime} ({formatTimeHHMM(rawDuration)})
                    </div>
                    <button onClick={handleQuickLogAll} className="flex items-center gap-1.5 bg-moss/70 text-white hover:bg-moss hover:text-white px-3 py-1.5 rounded-xl font-black uppercase tracking-widest text-[10px] transition-colors shadow-sm">
                        <Zap size={14} /> Snabblog
                    </button>
                </div>
            </div>

            <div className="space-y-2">
                {displayYouth.map(youth => (
                    <YouthAttendanceRow
                        key={youth.id}
                        youth={youth}
                        entry={attendance[getAttendanceKey(currentDate, youth.id, shiftId)]}
                        currentDate={currentDate}
                        shiftId={shiftId}
                        team={team}
                        actualDuration={actualDuration}
                        onMarkStandard={() => handleMarkStandard(youth.id)}
                        setManualAttendance={setManualAttendance}
                        removeAttendanceEntry={removeAttendanceEntry}
                    />
                ))}

                {availableExtras.length > 0 && (
                    <div className="pt-3 mt-3 border-t border-slate-teal/5">
                        <select value="" onChange={(e) => { if (e.target.value) addPendingAttendance(currentDate, e.target.value, shiftId); }} className="bg-white border border-slate-teal/10 p-3 rounded-2xl font-bold text-slate-teal text-sm w-full outline-none shadow-sm">
                            <option value="">+ Lägg till extra person...</option>
                            {availableExtras.map(y => <option key={y.id} value={y.id}>{y.name}</option>)}
                        </select>
                    </div>
                )}
            </div>
        </div>
    );
};