import React, { useState, useEffect, useRef } from 'react';
import {
    Dialog, DialogTitle, DialogContent, DialogActions,
    Button, Box, Typography, Table, TableHead,
    TableBody, TableRow, TableCell, CircularProgress, Alert,
    Autocomplete, TextField,
} from '@mui/material';
import { useAuth } from '../../../../../../contexts/AuthContext';

export interface PeriodTemplate {
    code: string;
    name: string;
    start_time: string;
    end_time: string;
    period_type: string;
}

interface ClassOption {
    id: string;
    name: string;
    class_code?: string;
    subject?: string;
    year_group?: string;
}

const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

function emptyGrid(): Record<string, Record<string, string>> {
    const g: Record<string, Record<string, string>> = {};
    DAYS.forEach(d => { g[d] = {}; });
    return g;
}

function classLabel(c: ClassOption): string {
    const parts = [c.class_code || c.name];
    if (c.year_group) parts.push(c.year_group);
    if (c.subject && c.subject !== c.name) parts.push(c.subject);
    return parts.join(' · ');
}

interface Props {
    open: boolean;
    onClose: () => void;
    onComplete: (timetableId: string) => void;
    apiBase: string;
    periodsTemplate: PeriodTemplate[];
    timetableId: string | null;
}

export function TeacherTimetableWizard({
    open,
    onClose,
    onComplete,
    apiBase,
    periodsTemplate,
    timetableId: initialTimetableId,
}: Props) {
    const { accessToken } = useAuth();
    const [localTimetableId, setLocalTimetableId] = useState<string | null>(initialTimetableId);
    const [initializing, setInitializing] = useState(false);
    const [loadingSlots, setLoadingSlots] = useState(false);
    const [loadingClasses, setLoadingClasses] = useState(false);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [grid, setGrid] = useState<Record<string, Record<string, string>>>(emptyGrid);
    const [classOptions, setClassOptions] = useState<ClassOption[]>([]);
    const slotsLoadedRef = useRef(false);

    const lessonPeriods = periodsTemplate.filter(p => p.period_type === 'lesson');
    const isEditing = !!initialTimetableId;

    // Reset when dialog opens
    useEffect(() => {
        if (!open) {
            slotsLoadedRef.current = false;
            return;
        }
        setLocalTimetableId(initialTimetableId);
        setGrid(emptyGrid());
        setError(null);
        slotsLoadedRef.current = false;
    }, [open, initialTimetableId]);

    // Load available classes for this institute
    useEffect(() => {
        if (!open || !accessToken || classOptions.length > 0) return;
        setLoadingClasses(true);
        fetch(`${apiBase}/database/timetable/classes?active_only=true&limit=200`, {
            headers: { Authorization: `Bearer ${accessToken}` },
        })
            .then(r => r.json())
            .then(data => {
                if (Array.isArray(data.classes)) {
                    setClassOptions(data.classes);
                }
            })
            .catch(() => {})
            .finally(() => setLoadingClasses(false));
    }, [open, accessToken, apiBase, classOptions.length]);

    // Auto-create TeacherTimetable node if not yet done
    useEffect(() => {
        if (!open || localTimetableId || !accessToken || initializing) return;
        setInitializing(true);
        setError(null);
        fetch(`${apiBase}/timetable/init`, {
            method: 'POST',
            headers: { Authorization: `Bearer ${accessToken}` },
        })
            .then(r => r.json())
            .then(data => {
                if (data.status === 'ok') {
                    setLocalTimetableId(data.timetable_id);
                } else {
                    setError(data.message || 'Could not initialize timetable. Has an admin set up the school calendar?');
                }
            })
            .catch(e => setError(e.message))
            .finally(() => setInitializing(false));
    }, [open, localTimetableId, accessToken, apiBase, initializing]);

    // Load existing slots when editing
    useEffect(() => {
        if (!open || !localTimetableId || !accessToken || slotsLoadedRef.current || loadingSlots) return;
        slotsLoadedRef.current = true;
        setLoadingSlots(true);
        fetch(`${apiBase}/timetable/slots`, {
            headers: { Authorization: `Bearer ${accessToken}` },
        })
            .then(r => r.json())
            .then(data => {
                if (data.status === 'ok' && Array.isArray(data.slots) && data.slots.length > 0) {
                    const g = emptyGrid();
                    for (const slot of data.slots) {
                        if (g[slot.day_of_week]) {
                            g[slot.day_of_week][slot.period_code] = slot.subject_class || '';
                        }
                    }
                    setGrid(g);
                }
            })
            .catch(() => {})
            .finally(() => setLoadingSlots(false));
    }, [open, localTimetableId, accessToken, apiBase, loadingSlots]);

    const setCell = (day: string, code: string, value: string) => {
        setGrid(prev => ({ ...prev, [day]: { ...prev[day], [code]: value } }));
    };

    const handleSave = async () => {
        if (!accessToken || !localTimetableId) return;
        setSaving(true);
        setError(null);
        try {
            const slots = [];
            for (const day of DAYS) {
                for (const period of lessonPeriods) {
                    const cls = (grid[day]?.[period.code] || '').trim();
                    if (cls) {
                        slots.push({
                            day_of_week: day,
                            period_code: period.code,
                            subject_class: cls,
                            start_time: period.start_time,
                            end_time: period.end_time,
                        });
                    }
                }
            }
            const res = await fetch(`${apiBase}/timetable/slots`, {
                method: 'POST',
                headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
                body: JSON.stringify({ timetable_id: localTimetableId, slots }),
            });
            const data = await res.json();
            if (data.status === 'ok') {
                onComplete(localTimetableId);
                handleClose();
            } else {
                setError(data.message || 'Save failed');
            }
        } catch (e: any) {
            setError(e.message);
        } finally {
            setSaving(false);
        }
    };

    const handleClose = () => {
        setError(null);
        setClassOptions([]);
        onClose();
    };

    const busy = initializing || loadingSlots || saving;

    return (
        <Dialog open={open} onClose={handleClose} maxWidth="lg" fullWidth>
            <DialogTitle sx={{ pb: 1 }}>
                {isEditing ? 'Edit My Timetable' : 'Set Up My Timetable'}
            </DialogTitle>

            <DialogContent>
                {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}

                {(initializing || loadingSlots) && (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, py: 2 }}>
                        <CircularProgress size={16} />
                        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                            {initializing ? 'Preparing your timetable…' : 'Loading existing classes…'}
                        </Typography>
                    </Box>
                )}

                {!initializing && !loadingSlots && localTimetableId && (
                    <Box>
                        <Typography variant="subtitle2" sx={{ mb: 0.5 }}>
                            Select or type a class name for each lesson slot (leave blank if free)
                        </Typography>
                        {classOptions.length > 0 && (
                            <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', mb: 1.5 }}>
                                {classOptions.length} class{classOptions.length !== 1 ? 'es' : ''} available — type to filter or enter a custom name
                            </Typography>
                        )}
                        <Box sx={{ overflowX: 'auto' }}>
                            <Table size="small">
                                <TableHead>
                                    <TableRow>
                                        <TableCell sx={{ fontWeight: 600, minWidth: 100 }}>Period</TableCell>
                                        {DAYS.map(d => (
                                            <TableCell key={d} align="center" sx={{ fontWeight: 600, minWidth: 130 }}>
                                                {d}
                                            </TableCell>
                                        ))}
                                    </TableRow>
                                </TableHead>
                                <TableBody>
                                    {lessonPeriods.map(period => (
                                        <TableRow key={period.code}>
                                            <TableCell>
                                                <Box>
                                                    <Typography variant="caption" sx={{ fontWeight: 600 }}>
                                                        {period.code}
                                                    </Typography>
                                                    <Typography variant="caption" sx={{ display: 'block', color: 'text.secondary' }}>
                                                        {period.start_time}–{period.end_time}
                                                    </Typography>
                                                </Box>
                                            </TableCell>
                                            {DAYS.map(day => (
                                                <TableCell key={day} align="center" sx={{ p: 0.5 }}>
                                                    <Autocomplete
                                                        freeSolo
                                                        size="small"
                                                        options={classOptions}
                                                        getOptionLabel={opt =>
                                                            typeof opt === 'string' ? opt : classLabel(opt)
                                                        }
                                                        value={grid[day]?.[period.code] || ''}
                                                        onChange={(_, val) => {
                                                            const text =
                                                                val === null ? ''
                                                                : typeof val === 'string' ? val
                                                                : classLabel(val);
                                                            setCell(day, period.code, text);
                                                        }}
                                                        onInputChange={(_, val) => setCell(day, period.code, val)}
                                                        renderInput={params => (
                                                            <TextField
                                                                {...params}
                                                                placeholder="—"
                                                                inputProps={{
                                                                    ...params.inputProps,
                                                                    style: {
                                                                        textAlign: 'center',
                                                                        fontSize: '0.78rem',
                                                                        padding: '3px 6px',
                                                                    },
                                                                }}
                                                                sx={{ width: 120 }}
                                                            />
                                                        )}
                                                        sx={{ width: 120 }}
                                                        disableClearable={false}
                                                        loading={loadingClasses}
                                                        noOptionsText="Type a class name"
                                                        ListboxProps={{ style: { maxHeight: 200 } }}
                                                    />
                                                </TableCell>
                                            ))}
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </Box>
                    </Box>
                )}
            </DialogContent>

            <DialogActions sx={{ px: 3, pb: 2 }}>
                <Button onClick={handleClose} disabled={busy}>Cancel</Button>
                <Button
                    onClick={handleSave}
                    variant="contained"
                    disabled={busy || !localTimetableId}
                >
                    {saving ? <CircularProgress size={18} /> : 'Save Timetable'}
                </Button>
            </DialogActions>
        </Dialog>
    );
}
