import React, { useState, useEffect } from "react";
import {
    Paper,
    TextField,
    FormControlLabel,
    Checkbox,
    TableContainer,
    Table,
    TableHead,
    TableBody,
    TableRow,
    TableCell,
    Switch,
    TableSortLabel,
    Box,
    FormControl,
    styled,
    Autocomplete,
    ThemeProvider,
    InputAdornment,
    IconButton,
    CircularProgress,
    Typography
} from "@mui/material";
import { Search as SearchIcon, Clear as ClearIcon } from "@mui/icons-material";
import QualificationDetails from "../../Qualification/Manage/QualificationDetails";
import CustomPagination from "../../Common/CustomPagination";
import theme from "../../Common/Theme";
import getIconComponent from "../../Common/CustomSortIcon";
import CustomDialog from "../../Qualification/Manage/CustomDialog";
import CheckIcon from "@mui/icons-material/Check";
import { grey } from "@mui/material/colors";

export const ProgressTracker = ({ baseUrl, defaultRowPerPageOptions }: {
    baseUrl: string,
    defaultRowPerPageOptions: any,
}) => {

    const [showAvailableOnly, setShowAvailableOnly] = useState(true);
    const [loading, setLoading] = useState<boolean>(false);
    const [search, setSearch] = useState<string>("");
    const [titleType, setTitleType] = useState<string>("");
    const [titleProvider, setTitleProvider] = useState<string>("");
    const [page, setPage] = useState(1);
    const [rowsPerPage, setRowsPerPage] = useState(30);
    const [totalRecords, setTotalRecords] = useState<number>(0);
    const [sortBy, setSortBy] = useState<string>('name');
    const [sortDirection, setSortDirection] = useState<string>('asc');
    const [qualificationList, setQualificationList] = useState<any[]>([]);
    const [types, setTypes] = useState<string[]>([]);
    const [providers, setProviders] = useState<string[]>([]);
    const [openModuleDialog, setOpenModuleDialog] = useState(false);
    const [moduleDialogTitle, setModuleDialogTitle] = useState("");
    const [moduleList, setModuleList] = useState<string[]>([]);
    const [selectedQualification, setSelectedQualification] = useState<number | null>(null);
    const [allQualifications, setAllQualifications] = useState<any[]>([]);
    const [openQualificationDialog, setOpenQualificationDialog] = useState(false);
    const [qualificationId, setQualificationId] = useState<number | undefined>();
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        setLoading(true);
        setError(null); // Reset error before fetching
    
        const currentParams = new URLSearchParams();
        currentParams.set('search', '');
        currentParams.set('page', '1');
        currentParams.set('rowsPerPage', 'all');
        if (showAvailableOnly) currentParams.set('availableOnly', '1');
    
        fetch(baseUrl + 'pt/qualifications?' + currentParams.toString(), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json'
            }
        })
        .then(resp => resp.json())
        .then(respJSON => {
            if (respJSON?.status === 'error') {
                setError(`Failed to load qualification data: ${respJSON.message}`);
                return;
            }
            setAllQualifications(respJSON?.data ?? []);
            setTypes(respJSON?.types ?? []);
            setProviders(respJSON?.providers ?? []);
        })
        .catch(error => {
            setError(`Failed to load qualification data.`);
        })
        .finally(() => setLoading(false));
    }, [baseUrl, showAvailableOnly]);
    
    

    useEffect(() => {
        let filtered = allQualifications.filter(q => {
            const matchesSearch =
                q.name.toLowerCase().includes(search.toLowerCase()) ||
                q.reference.toLowerCase().includes(search.toLowerCase());
            const matchesType = titleType ? q.type === titleType : true;
            const matchesProvider = titleProvider ? q.provider === titleProvider : true;
            const matchesAvailability = showAvailableOnly ? q.available === true : true;

            return matchesSearch && matchesType && matchesProvider && matchesAvailability;
        });

        filtered = filtered.sort((a, b) => {
            let valA = a[sortBy];
            let valB = b[sortBy];
        
            if (sortBy === 'module_count') {
                valA = typeof valA === 'number' ? valA : 0;
                valB = typeof valB === 'number' ? valB : 0;
                return sortDirection === 'asc' ? valA - valB : valB - valA;
            } else {
                const strA = valA?.toString().toLowerCase() ?? '';
                const strB = valB?.toString().toLowerCase() ?? '';
                if (strA < strB) return sortDirection === 'asc' ? -1 : 1;
                if (strA > strB) return sortDirection === 'asc' ? 1 : -1;
                return 0;
            }
        });

        setTotalRecords(filtered.length);
        const start = (page - 1) * rowsPerPage;
        setQualificationList(filtered.slice(start, start + rowsPerPage));
    }, [search, allQualifications, page, rowsPerPage, sortBy, sortDirection, titleType, titleProvider, showAvailableOnly]);

    const handleSort = (column: string, direction: string) => {
        setPage(1);
        setSortBy(column);
        setSortDirection(direction);
    };

    const handleModuleCellClick = (qualificationName: string, modules: (string | { name?: string; code?: string })[]) => {
        setModuleDialogTitle(`Modules for ${qualificationName}`);
        const namesList = modules.map(m => typeof m === 'string' ? m : m?.name || m?.code || "Unnamed Module");
        setModuleList(namesList);
        setOpenModuleDialog(true);
    };

    const handleClose = () => {
        setOpenQualificationDialog(false);
        setOpenModuleDialog(false);
        setQualificationId(undefined);
    };

    const GreenSwitch = styled(Switch)(() => ({
        "& .MuiSwitch-switchBase.Mui-checked": {
            color: "#067a40",
            "&:hover": { backgroundColor: "rgba(6, 122, 64, 0.08)" },
        },
        "& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track": {
            backgroundColor: "#067a40",
        },
    }));

    const toggleQualificationAvailability = (id: number, available: boolean) => {
        setError(null); // Reset error before toggling
    
        fetch(`${baseUrl}pt/qualifications/${id}/toggleAvailability`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json'
            },
        })
        .then(resp => resp.json())
        .then(respJSON => {
            if (respJSON.status === 'error') {
                setError(`Failed to update availability for qualification ${id}: ${respJSON.message}`);
                return;
            }
            setQualificationList(prev =>
                prev.map(q => q.id === id ? { ...q, available: !available } : q)
            );
        })
        .catch(error => {
            setError(`Toggle availability failed`);
        });
    };    
    

    return (
        <ThemeProvider theme={theme}>
            {error && (
            <Box display="flex" justifyContent="center" mb={2}>
                <Typography variant="div" sx={{background: "url(/Static/Icons/ui/ux2/appbar-alert.png) 0px -3px no-repeat", backgroundSize: "contain", display:"inline-block", backgroundColor: "var(--red)", color: "#ffffff", padding: "0.7em 1.5em 1.0em 3em", borderRadius: "0.25em", fontSize: "1em"}}>
                {error}
                </Typography>
            </Box>
            )}

            <Box sx={{ margin: "auto", p: 3, boxShadow: 3, borderRadius: 2, width: '100%' }}>
                <Box sx={{ display: "flex", flexWrap: 'wrap', gap: 2, mb: 2 }}>
                <TextField
                    variant="outlined"
                    label="Search Qualification/Reference"
                    value={search}
                    InputProps={{
                        'aria-label': 'Search qualifications',
                        endAdornment: (
                        <InputAdornment position="end">
                            {search && (
                            <IconButton
                                aria-label="Clear search"
                                onClick={() => setSearch('')}
                                edge="end"
                                size="small"
                            >
                                <ClearIcon fontSize="small" />
                            </IconButton>
                            )}
                            <SearchIcon />
                        </InputAdornment>
                        ),
                    }}
                    sx={{
                        "& .MuiInputBase-input": {
                        padding: "16.5px 14px !important",
                        border: "none",
                        },
                        "& .MuiInputBase-input:focus": {
                        outline: "unset !important",
                        },
                        flex: '1 1 400px',
                    }}
                    onChange={(e) => setSearch(e.target.value)}
                    />


                    <FormControl sx={{ flex: '1 1 200px' }}>
                        <Autocomplete
                            disablePortal
                            options={types} // Ensure options is always an array
                            value={titleType || null} // Controlled component
                            onChange={(_event, newValue) => {
                                setPage(1); // Reset page on filter change
                                setTitleType(newValue ?? ''); // Ensure default value is ''
                            }}
                            renderInput={(params) => <TextField {...params} label="Type" />}
                        />
                    </FormControl>

                    <FormControl sx={{ flex: '1 1 200px' }}>
                        <Autocomplete
                            disablePortal
                            options={providers} // Ensure options is always an array
                            value={titleProvider || null} // Controlled component
                            onChange={(_event, newValue) => {
                                setPage(1); // Reset page on filter change
                                setTitleProvider(newValue ?? ''); // Ensure default value is ''
                            }}
                            renderInput={(params) => <TextField {...params} label="Provider" />}
                        />
                    </FormControl>

                    <FormControlLabel
                    label="Show available only"
                    sx={{ '.MuiFormControlLabel-label': {
                            marginLeft: '4px',
                            color: '#000000de', // Add space between checkbox and label
                        },
                        ml: 0.3 }}
                    control={
                        <Checkbox
                            checked={showAvailableOnly}
                            onChange={(event) => setShowAvailableOnly(event.target.checked)}  // Update state when toggled
                            aria-label="Show Available Only"
                            icon={
                                <Box  
                                    sx={{
                                        width: 20,
                                        height: 20,
                                        border: `1px solid #000000de`,
                                        borderRadius: '4px',
                                        backgroundColor: '#fff',
                                    }}
                                />
                            }
                            checkedIcon={
                                <Box
                                    sx={{
                                        width: 20,
                                        height: 20,
                                        border: `1px solid #000000de`,
                                        borderRadius: '4px',
                                        backgroundColor: '#fff',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                    }}
                                >
                                    <CheckIcon sx={{ fontSize: 18, color: grey[700] }} />
                                </Box>
                            }
                            sx={{
                                padding: 0,
                            }}
                        />
                    }
                />

                </Box>

                {/* --- Table Area --- */}
                <TableContainer component={Paper} sx={{mb: 2}}>
                    <Table stickyHeader aria-label="Qualifications Table">
                        <TableHead>
                            <TableRow>
                                <TableCell>
                                    <TableSortLabel
                                        active={sortBy === 'name'}
                                        direction={sortDirection === 'desc' ? 'desc' : 'asc'}
                                        onClick={() => handleSort('name', sortDirection === 'asc' ? 'desc' : 'asc')}
                                        IconComponent={getIconComponent(sortBy === 'name', sortDirection === 'desc' ? 'desc' : 'asc')}
                                    >
                                        Qualification
                                    </TableSortLabel>
                                </TableCell>
                                <TableCell>
                                    <TableSortLabel
                                        active={sortBy === 'reference'}
                                        direction={sortBy === 'reference' ? sortDirection as 'asc' | 'desc' : 'asc'}
                                        onClick={() => handleSort('reference', sortBy === 'reference' && sortDirection === 'asc' ? 'desc' : 'asc')}
                                        IconComponent={getIconComponent(sortBy === 'reference', sortDirection === 'desc' ? 'desc' : 'asc')}
                                    >
                                        Reference
                                    </TableSortLabel>
                                </TableCell>
                                <TableCell>
                                    <TableSortLabel
                                        active={sortBy === 'provider'}
                                        direction={sortBy === 'provider' ? sortDirection as 'asc' | 'desc' : 'asc'}
                                        onClick={() => handleSort('provider', sortBy === 'provider' && sortDirection === 'asc' ? 'desc' : 'asc')}
                                        IconComponent={getIconComponent(sortBy === 'provider', sortDirection === 'desc' ? 'desc' : 'asc')}
                                    >
                                        Provider
                                    </TableSortLabel>
                                </TableCell>
                                <TableCell>
                                     <TableSortLabel
                                        active={sortBy === 'type'}
                                        direction={sortDirection === 'desc' ? 'desc' : 'asc'}
                                        onClick={() => handleSort('type', sortDirection === 'asc' ? 'desc' : 'asc')}
                                        IconComponent={getIconComponent(sortBy === 'type', sortDirection === 'desc' ? 'desc' : 'asc')}
                                    >
                                        Type
                                    </TableSortLabel>
                                </TableCell>
                                <TableCell>
                                    <TableSortLabel
                                        active={sortBy === 'module_count'}
                                        direction={sortBy === 'module_count' ? sortDirection as 'asc' | 'desc' : 'asc'}
                                        onClick={() => handleSort('module_count', sortBy === 'module_count' && sortDirection === 'asc' ? 'desc' : 'asc')}
                                        IconComponent={getIconComponent(sortBy === 'module_count', sortDirection === 'desc' ? 'desc' : 'asc')}>
                                        Linked Modules
                                    </TableSortLabel>
                                </TableCell>
                                <TableCell align="center">Availability</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {loading ? (
                                <TableRow>
                                   <Box display="flex" justifyContent="center" py={4}>
                                    <CircularProgress />
                                    </Box>
                                </TableRow>
                            ) : qualificationList.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={6} align="center">No qualifications found.</TableCell>
                                </TableRow>
                            ) : (
                                    qualificationList.map((row) => (
                                    <TableRow key={row.id} hover>
                                        <TableCell>
                                            <Box
                                                component="span"
                                                onClick={() => {
                                                setQualificationId(row.id);
                                                setOpenQualificationDialog(true);
                                                }}
                                                sx={{
                                                cursor: 'pointer',
                                                color: 'primary.main', // Use theme color
                                                textDecoration: 'underline', // Always underline
                                                display: 'inline-block',
                                                }}
                                                role="button"
                                                tabIndex={0}
                                                aria-label={`View details for ${row.name}`}
                                                onKeyDown={(e) => {
                                                if (e.key === 'Enter' || e.key === ' ') {
                                                    setQualificationId(row.id);
                                                    setOpenQualificationDialog(true);
                                                }
                                                }}
                                            >
                                                {row.name}
                                            </Box>
                                            </TableCell>

                                        <TableCell>{row.reference}</TableCell>
                                        <TableCell>{row.provider}</TableCell>
                                        <TableCell>{row.type}</TableCell>
                                        <TableCell align="center">
                                            <Box
                                                component="span"
                                                onClick={() => handleModuleCellClick(row.name, row.modules || [])}
                                                sx={{
                                                    cursor: 'pointer',
                                                    color: 'primary.main',
                                                    textDecoration: 'underline',
                                                    display: 'inline-block',
                                                }}
                                                role="button"
                                                tabIndex={0}
                                                aria-label={`View modules for ${row.name}`}
                                                onKeyDown={(e) => {
                                                    if (e.key === 'Enter' || e.key === ' ') {
                                                        handleModuleCellClick(row.name, row.modules || []);
                                                    }
                                                }}
                                            >
                                                {row.module_count || 0}
                                            </Box>
                                        </TableCell>

                                        <TableCell align="center">
                                            <GreenSwitch
                                                checked={row.available}
                                                onChange={() => toggleQualificationAvailability(row.id, row.available)}
                                                inputProps={{ 'aria-label': `Toggle availability for ${row.name}` }}
                                            />
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </TableContainer>

                {/* --- Pagination --- */}
               {totalRecords > 0 && ( // Conditionally render pagination
                    <CustomPagination
                        totalRecords={totalRecords}
                        page={page}
                        rowsPerPage={rowsPerPage}
                        onPageChange={(newPage: number) => setPage(newPage)}
                        onRowsPerPageChange={(newRows: number) => {
                            setPage(1); // Reset page when changing rows per page
                            setRowsPerPage(newRows);
                        }}
                        rowsPerPageOptions={defaultRowPerPageOptions}
                    />
                )}

                <CustomDialog
                    open={openQualificationDialog}
                    onClose={handleClose} // Use the combined close handler
                    title="Qualification Details" // More specific title
                    cancelText="Close"
                    showTitle={true}
                    showContent={true}
                    showActions={true} // Keep actions for the Close button
                    dialogSize="md">
                    {/* Conditionally render details only when ID is set */}
                    {qualificationId !== undefined && (
                        <QualificationDetails baseUrl={baseUrl} qualificationId={qualificationId}/>
                    )}
                </CustomDialog>

                {/* TODO: Add Module List Dialog similar to QualificationDetails if needed */}
                <CustomDialog
                    open={openModuleDialog}
                    onClose={handleClose} // Use the combined close handler
                    title={moduleDialogTitle}
                    cancelText="Close"
                    showTitle={true}
                    showContent={true}
                    showActions={true}
                    dialogSize="sm"> 
                    <Box sx={{ p: 2 }}>
                        {moduleList.length > 0 ? (
                            <ul>
                                {moduleList.map((moduleName, index) => (
                                    <li key={index}>{moduleName}</li>
                                ))}
                            </ul>
                        ) : (
                            <p>No modules linked.</p>
                        )}
                    </Box>
                </CustomDialog>
            </Box>
        </ThemeProvider>
    );
};
