// app/admin/SetupTab.tsx

"use client";

import { CalendarRange, Trash2, UserPlus } from 'lucide-react';
import Image from 'next/image';
import React, { useState } from 'react';
import falconIcon from '../assets/falcon.svg';
import porpoiseIcon from '../assets/porpoise.svg';
import { type Period, type Youth } from './adminTypes';

interface Props {
    periods: Period[];
    createPeriod: (name: string, start: string) => void;
    deletePeriod: (id: string) => void;
    bulkAddYouth: (periodId: string, text: string, team: 'PF' | 'TU') => void;
    removeYouth: (periodId: string, youthId: string) => void;
    isOffline: boolean;
}

export const SetupTab: React.FC<Props> = ({ periods, createPeriod, deletePeriod, bulkAddYouth, removeYouth, isOffline }) => {
    const [bulkText, setBulkText] = useState('');
    const [bulkTeam, setBulkTeam] = useState<'PF' | 'TU'>('PF');
    const [expandedPeriod, setExpandedPeriod] = useState<string | null>(null);

    const handleCreate = () => {
        if (isOffline) {
            alert("Du måste vara ansluten till internet för att skapa en ny period.");
            return;
        }
        const name = (document.getElementById('periodName') as HTMLInputElement).value;
        const start = (document.getElementById('periodStart') as HTMLInputElement).value;
        if (name && start) createPeriod(name, start);
    };

    const handleDeletePeriod = (id: string) => {
        if (isOffline) {
            alert("Åtgärd nekad: Du måste vara ansluten till internet för att ta bort en period.");
            return;
        }
        if (window.confirm('Är du säker på att du vill ta bort hela perioden? All närvarodata kopplad till perioden kommer försvinna!')) {
            deletePeriod(id);
        }
    };

    const handleRemoveYouth = (periodId: string, youthId: string, youthName: string) => {
        if (isOffline) {
            alert("Åtgärd nekad: Du måste vara ansluten till internet för att ta bort en ungdom.");
            return;
        }
        if (window.confirm(`Är du säker på att du vill ta bort ${youthName} från perioden?`)) {
            removeYouth(periodId, youthId);
        }
    };

    const handleBulkAdd = () => {
        if (isOffline) {
            alert("Åtgärd nekad: Du måste vara ansluten till internet för att importera ungdomar.");
            return;
        }
        if (expandedPeriod) {
            const processedText = bulkText.split('\n').map(line => {
                const parts = line.split(/[,|-]/).map(p => p.trim());
                if (parts.length > 1) {
                    const t = parts[1].toUpperCase();
                    if (t === 'P' || t === 'PILGRIMSFALK' || t === 'PILGRIMSFALKARNA') parts[1] = 'PF';
                    if (t === 'T' || t === 'TUMLARE' || t === 'TUMLARNA') parts[1] = 'TU';
                    return parts.join(', ');
                }
                return line;
            }).join('\n');

            bulkAddYouth(expandedPeriod, processedText, bulkTeam);
            setBulkText('');
        }
    };

    // Helper to render a group of youth
    const renderYouthGroup = (youthList: Youth[], periodId: string) => {
        if (youthList.length === 0) return null;

        return (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-6">
                {youthList.map(youth => (
                    <div key={youth.id} className="flex justify-between items-center bg-white border border-slate-teal/10 p-3 rounded-lg">
                        <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-lg">{youth.name}</span>
                        </div>
                        <button
                            onClick={() => handleRemoveYouth(periodId, youth.id, youth.name)}
                            className={`transition-colors ${isOffline ? 'text-goldenrod/40 cursor-not-allowed' : 'text-goldenrod hover:text-red-500'}`}
                            title={isOffline ? "Kräver internet" : "Ta bort ungdom"}
                        >
                            <Trash2 size={16} />
                        </button>
                    </div>
                ))}
            </div>
        );
    };

    return (
        <div className="space-y-6 animate-fade-in">
            {/* Create New Period */}
            <div className="bg-eggshell border-2 border-slate-teal/20 p-6 rounded-2xl shadow-sm">
                <h2 className="text-xl font-black text-ebony uppercase tracking-widest flex items-center mb-6">
                    <CalendarRange className="mr-3 text-slate-teal" size={24} />
                    Skapa Ny Period
                </h2>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <input type="text" id="periodName" placeholder="T.ex. Period 1" className="w-full bg-white border border-slate-teal/20 p-3 rounded-lg font-bold" disabled={isOffline} />
                    <input type="date" id="periodStart" className="w-full bg-white border border-slate-teal/20 p-3 rounded-lg font-bold" disabled={isOffline} />
                    <button onClick={handleCreate} disabled={isOffline} className="bg-slate-teal text-eggshell font-black uppercase px-6 py-3 rounded-lg hover:bg-ebony transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
                        Starta
                    </button>
                </div>
            </div>

            {/* List Existing Periods */}
            {periods.map(period => {
                // Sort by name alphabetically
                const pfYouth = period.youthList.filter(y => y.team === 'PF').sort((a, b) => a.name.localeCompare(b.name));
                const tuYouth = period.youthList.filter(y => y.team === 'TU').sort((a, b) => a.name.localeCompare(b.name));

                return (
                    <div key={period.id} className="bg-eggshell border-2 border-slate-teal/20 rounded-2xl shadow-sm overflow-hidden">
                        <div className="p-6 flex justify-between items-center cursor-pointer hover:bg-slate-teal/5" onClick={() => setExpandedPeriod(expandedPeriod === period.id ? null : period.id)}>
                            <div>
                                <h3 className="text-lg font-black text-ebony uppercase">{period.name}</h3>
                                <p className="text-sm font-bold text-moss">{period.startDate} till {period.endDate} • {period.youthList.length} ungdomar</p>
                            </div>
                            <button
                                onClick={(e) => { e.stopPropagation(); handleDeletePeriod(period.id); }}
                                className={`p-2 transition-colors ${isOffline ? 'text-goldenrod/40 cursor-not-allowed' : 'text-goldenrod/80 hover:text-goldenrod'}`}
                                title={isOffline ? "Kräver internet" : "Ta bort period"}
                            >
                                <Trash2 size={20} />
                            </button>
                        </div>

                        {/* Expandable Youth Management */}
                        {expandedPeriod === period.id && (
                            <div className="p-6 border-t border-slate-teal/10 bg-slate-teal/5">
                                <h4 className="font-black text-ebony mb-4 flex items-center"><UserPlus size={18} className="mr-2 text-slate-teal" /> Bulk-lägg till ungdomar</h4>
                                <div className="flex flex-col md:flex-row gap-4 mb-6">
                                    <textarea
                                        value={bulkText}
                                        onChange={(e) => setBulkText(e.target.value)}
                                        placeholder="Klistra in namn, ett per rad.&#10;T.ex. 'Anna' eller 'Anna, P'"
                                        className="w-full h-24 bg-white border border-slate-teal/20 p-3 rounded-lg font-bold resize-none"
                                        disabled={isOffline}
                                    />
                                    <div className="flex flex-col gap-2 shrink-0">
                                        <select value={bulkTeam} onChange={(e) => setBulkTeam(e.target.value as 'PF' | 'TU')} className="bg-white border border-slate-teal/20 p-3 rounded-lg font-bold" disabled={isOffline}>
                                            <option value="PF">Standard: Pilgrimsfalk (P)</option>
                                            <option value="TU">Standard: Tumlare (T)</option>
                                        </select>
                                        <button onClick={handleBulkAdd} disabled={isOffline} className="bg-slate-teal text-eggshell font-black uppercase px-6 py-3 rounded-lg hover:bg-ebony transition-colors h-full disabled:opacity-50 disabled:cursor-not-allowed">
                                            Importera
                                        </button>
                                    </div>
                                </div>

                                {pfYouth.length > 0 && <h4 className="text-xs font-black text-moss uppercase tracking-widest mb-3">Pilgrimsfalkarna</h4>}
                                {renderYouthGroup(pfYouth, period.id)}

                                {tuYouth.length > 0 && <h4 className="text-xs font-black text-moss uppercase tracking-widest mb-3">Tumlarna</h4>}
                                {renderYouthGroup(tuYouth, period.id)}
                            </div>
                        )}
                    </div>
                );
            })}
        </div>
    );
};