import React, { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { DataGrid } from '@mui/x-data-grid';
import { csCZ } from '@mui/x-data-grid/locales';
import { useUser } from '../contexts/UserContext';
import { Role } from '../types/user';
import {
    Dialog,
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
    Button,
    Chip
} from '@mui/material';
import api from '../utils/api';
import { mapToName, statusColor } from '../utils/cz_uk';

const AdminTable = () => {
    const [rows, setRows] = React.useState<any[]>([]);
    const [status, setStatus] = React.useState("");
    const [search, setSearch] = React.useState("");
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const [dialogType, setDialogType] = React.useState<'approve' | 'reject' | null>(null);
    const { user } = useUser();
    const [selectedIds, setSelectedIds] = React.useState<any[]>([]);

    useEffect(() => {
        api.get('/editor/all')
            .then((response) => {
                setRows(response.data.articles.map((article: any) => ({
                    id: article.id,
                    name: article.title,
                    author: article.author,
                    date: new Date(article.created_at).toLocaleString('cs-CZ', {
                        day: 'numeric',
                        month: 'long',
                        year: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                    }),
                    status: article.status,
                })));
            })
            .catch((error) => {
                console.error("Failed to load articles", error);
            });
    }, []);

    const handleConfirm = async () => {
        try {
            const payload = {
                ids: selectedIds,
            };

            const endpoint = dialogType === 'approve' ? '/editor/APPROVED' : '/editor/REJECTED';
            await api.post(endpoint, payload);

            const response = await api.get('/editor/all');
            setRows(response.data.articles.map((article: any) => ({
                id: article.id,
                name: article.title,
                author: article.author,
                date: new Date(article.created_at).toLocaleString('cs-CZ', {
                    day: 'numeric',
                    month: 'long',
                    year: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                }),
                status: article.status,
            })));
        } catch (error) {
            console.error("Failed to update or reload articles", error);
        }

        setDialogOpen(false);
    };

    const openDialog = (type: 'approve' | 'reject') => {
        setDialogType(type);
        setDialogOpen(true);
    };

    const possibleStatus = [
        { code: "IN_PROGRESS", label: mapToName("IN_PROGRESS") },
        { code: "APPROVED", label: mapToName("APPROVED") },
        { code: "REJECTED", label: mapToName("REJECTED") }
    ];

    const columns = [
        {
            field: 'name',
            headerName: 'Název článku',
            flex: 1,
            renderCell: (params: any) => (
                <Link to={`/article_preview/${params.row.id}`}>
                    {params.value}
                </Link>
            )
        },
        { field: 'author', headerName: 'Jméno autora', flex: 1 },
        { field: 'date', headerName: 'Datum vytvoření', flex: 1 },
        {
            field: 'status',
            headerName: 'Stav',
            flex: 1,
            renderCell: (params: any) => (
                <Chip
                    label={mapToName(params.value)}
                    color={statusColor(params.value)}
                />
            )
        },
    ];

    const filteredRows = rows.filter((row: any) => {
        const matchesStatus = status ? row.status === status : true;
        const matchesSearch = search
            ? row.name.toLowerCase().includes(search.toLowerCase()) ||
              row.author.toLowerCase().includes(search.toLowerCase())
            : true;
        return matchesStatus && matchesSearch;
    });

    if (user?.role !== Role.SPRAVCE) {
        return (
            <div className="max-w-6xl mx-auto px-4 py-8">
                <h2 className="text-xl text-green-950 font-bold text-center mb-8">
                    Nemáte oprávnění k zobrazení této stránky.
                </h2>
            </div>
        );
    }

    return (
        <div className="max-w-6xl mx-auto px-4 py-8 bg-yellow-50">
            <div className="flex flex-row justify-between m-4">
                <select
                    id="status-filter"
                    value={status}
                    onChange={(e) => setStatus(e.target.value)}
                    className="px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                >
                    <option value="">Všechny články</option>
                    {possibleStatus.map((option) => (
                        <option key={option.code} value={option.code}>
                            {option.label}
                        </option>
                    ))}
                </select>
                <div>
                    <input
                        type="text"
                        placeholder="Hledat článek..."
                        onChange={(e) => setSearch(e.target.value)}
                        className="p-2 bg-yellow-200 border-gray-300 rounded"
                    />
                </div>
            </div>

            <DataGrid
                rows={filteredRows}
                columns={columns}
                checkboxSelection
                onRowSelectionModelChange={(ids) => setSelectedIds(ids)}
                localeText={csCZ.components.MuiDataGrid.defaultProps.localeText}
            />

            <div className="flex gap-2 my-4">
                <button
                    className="bg-green-950 hover:bg-green-800 text-white py-2 px-4 rounded"
                    onClick={() => openDialog('approve')}
                >
                    Schválit označené
                </button>
                <button
                    className="bg-red-600 hover:bg-red-800 text-white py-2 px-4 rounded"
                    onClick={() => openDialog('reject')}
                >
                    Zamítnout označené
                </button>
            </div>

            <Dialog
                open={dialogOpen}
                onClose={() => setDialogOpen(false)}
                aria-labelledby="confirm-dialog-title"
                aria-describedby="confirm-dialog-description"
            >
                <DialogTitle id="confirm-dialog-title">
                    {dialogType === 'approve' ? 'Potvrdit schválení' : 'Potvrdit zamítnutí'}
                </DialogTitle>
                <DialogContent>
                    <DialogContentText id="confirm-dialog-description">
                        Opravdu chcete {dialogType === 'approve' ? 'schválit' : 'zamítnout'} vybrané články?
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setDialogOpen(false)} color="primary">
                        Ne
                    </Button>
                    <Button onClick={handleConfirm} color={dialogType === 'approve' ? 'success' : 'error'} autoFocus>
                        Ano
                    </Button>
                </DialogActions>
            </Dialog>
        </div>
    );
};

export default AdminTable;
