import { useRef, useState } from "react";
import { Modal, Button, Alert, Form } from "react-bootstrap";

type Props = {
    isOpen: boolean;
    onClose: () => void;
};

/** Modální dialog pro přenačtení menu z restaurací. */
export default function RefreshMenuModal({ isOpen, onClose }: Readonly<Props>) {
    const refreshPassRef = useRef<HTMLInputElement>(null);
    const refreshTypeRef = useRef<HTMLSelectElement>(null);
    const [refreshLoading, setRefreshLoading] = useState(false);
    const [refreshMessage, setRefreshMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);

    const handleRefresh = async () => {
        const password = refreshPassRef.current?.value;
        const type = refreshTypeRef.current?.value;
        if (!password || !type) {
            setRefreshMessage({ type: 'error', text: 'Zadejte heslo a typ refresh.' });
            return;
        }

        setRefreshLoading(true);
        setRefreshMessage(null);

        try {
            const res = await fetch(`/api/food/refresh?type=${type}&heslo=${encodeURIComponent(password)}`);
            const data = await res.json();
            if (res.ok) {
                setRefreshMessage({ type: 'success', text: 'Uspesny fetch' });
                if (refreshPassRef.current) {
                    refreshPassRef.current.value = '';
                }
            } else {
                setRefreshMessage({ type: 'error', text: data.error || 'Chyba při obnovování jídelníčku.' });
            }
        } catch (error) {
            console.error('Error refreshing menu:', error);
            setRefreshMessage({ type: 'error', text: 'Chyba při obnovování jídelníčku.' });
        } finally {
            setRefreshLoading(false);
        }
    };

    const handleClose = () => {
        setRefreshMessage(null);
        onClose();
    };

    return (
        <Modal show={isOpen} onHide={handleClose}>
            <Modal.Header closeButton>
                <Modal.Title><h2>Přenačtení menu</h2></Modal.Title>
            </Modal.Header>
            <Modal.Body>
                <p>Ruční refresh dat z restaurací.</p>

                {refreshMessage && (
                    <Alert variant={refreshMessage.type === 'success' ? 'success' : 'danger'}>
                        {refreshMessage.text}
                    </Alert>
                )}

                <Form.Group className="mb-3">
                    <Form.Label>Heslo</Form.Label>
                    <Form.Control
                        ref={refreshPassRef}
                        type="password"
                        placeholder="Zadejte heslo"
                        onKeyDown={e => e.stopPropagation()}
                    />
                </Form.Group>

                <Form.Group className="mb-3">
                    <Form.Label>Typ refreshe</Form.Label>
                    <Form.Select ref={refreshTypeRef} defaultValue="week">
                        <option value="week">Týden</option>
                        <option value="day">Den</option>
                    </Form.Select>
                </Form.Group>

                <Button
                    onClick={handleRefresh}
                    disabled={refreshLoading}
                >
                    {refreshLoading ? 'Načítám...' : 'Obnovit menu'}
                </Button>
            </Modal.Body>
            <Modal.Footer>
                <Button variant="secondary" onClick={handleClose}>
                    Zavřít
                </Button>
            </Modal.Footer>
        </Modal>
    );
}
