import { useState } from "react";
import { Modal, Button, Form, ListGroup, Alert } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrashCan } from "@fortawesome/free-regular-svg-icons";
import { faPlus, faUpRightFromSquare, faXmark } from "@fortawesome/free-solid-svg-icons";
import { addStore, deleteStore, Store } from "../../../../types";
import { getStoreUrls, storeUrlLabel } from "../../utils/storeUrls";

type Props = {
    isOpen: boolean;
    onClose: () => void;
    stores: Store[];
    onStoresChanged: (stores: Store[]) => void;
};

export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChanged }: Readonly<Props>) {
    const [newName, setNewName] = useState('');
    // Jeden podnik může být dostupný přes více dovozových služeb — proto seznam URL
    const [newUrls, setNewUrls] = useState<string[]>(['']);
    const [heslo, setHeslo] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const setUrlAt = (index: number, value: string) =>
        setNewUrls(prev => prev.map((u, i) => (i === index ? value : u)));

    const addUrlRow = () => setNewUrls(prev => [...prev, '']);

    const removeUrlRow = (index: number) =>
        setNewUrls(prev => (prev.length === 1 ? [''] : prev.filter((_, i) => i !== index)));

    const handleAdd = async () => {
        if (!newName.trim()) return;
        setError(null);
        setLoading(true);
        try {
            const urls = newUrls.map(u => u.trim()).filter(Boolean);
            const res = await addStore({ body: { name: newName.trim(), urls: urls.length > 0 ? urls : undefined, heslo } });
            if (res.error) {
                setError((res.error as any).error || 'Nastala chyba');
            } else if (res.data) {
                onStoresChanged(res.data as Store[]);
                setNewName('');
                setNewUrls(['']);
            }
        } catch (e: any) {
            setError(e.message || 'Nastala chyba');
        } finally {
            setLoading(false);
        }
    };

    const handleRemove = async (name: string) => {
        setError(null);
        setLoading(true);
        try {
            const res = await deleteStore({ body: { name, heslo } });
            if (res.error) {
                setError((res.error as any).error || 'Nastala chyba');
            } else if (res.data) {
                onStoresChanged(res.data as Store[]);
            }
        } catch (e: any) {
            setError(e.message || 'Nastala chyba');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal show={isOpen} onHide={onClose}>
            <Modal.Header closeButton>
                <Modal.Title><h2>Správa obchodů</h2></Modal.Title>
            </Modal.Header>
            <Modal.Body>
                {error && (
                    <Alert variant="danger" onClose={() => setError(null)} dismissible>
                        {error}
                    </Alert>
                )}

                <Form.Group className="mb-3">
                    <Form.Label>Admin heslo</Form.Label>
                    <Form.Control
                        type="password"
                        placeholder="Heslo"
                        value={heslo}
                        onChange={e => setHeslo(e.target.value)}
                        onKeyDown={e => e.stopPropagation()}
                    />
                </Form.Group>

                <hr />
                <h6>Přidat obchod</h6>
                <Form.Control
                    className="mb-2"
                    type="text"
                    placeholder="Název obchodu"
                    value={newName}
                    onChange={e => setNewName(e.target.value)}
                    onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleAdd(); }}
                />
                {newUrls.map((url, index) => (
                    <div key={index} className="d-flex gap-2 mb-2 align-items-center">
                        <Form.Control
                            type="url"
                            placeholder={index === 0
                                ? 'URL na nabídku (volitelné, např. Bolt Food/Wolt)'
                                : 'Další URL na nabídku (jiná dovozová služba)'}
                            value={url}
                            onChange={e => setUrlAt(index, e.target.value)}
                            onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleAdd(); }}
                        />
                        <Button
                            variant="outline-secondary"
                            onClick={() => removeUrlRow(index)}
                            disabled={newUrls.length === 1 && !url}
                            title="Odebrat tuto URL"
                        >
                            <FontAwesomeIcon icon={faXmark} />
                        </Button>
                    </div>
                ))}
                <div className="d-flex justify-content-between align-items-center mb-3">
                    <Button variant="link" size="sm" className="p-0" onClick={addUrlRow}>
                        <FontAwesomeIcon icon={faPlus} className="me-1" />
                        Přidat další URL
                    </Button>
                    <Button variant="primary" onClick={handleAdd} disabled={loading || !newName.trim() || !heslo}>
                        Přidat
                    </Button>
                </div>

                <h6>Aktuální seznam</h6>
                {stores.length === 0 ? (
                    <p className="text-muted">Žádné obchody v seznamu</p>
                ) : (
                    <ListGroup>
                        {stores.map(s => {
                            const urls = getStoreUrls(s);
                            return (
                                <ListGroup.Item key={s.name} className="d-flex justify-content-between align-items-start">
                                    <div>
                                        <div>{s.name}</div>
                                        {urls.length > 0 && (
                                            <small className="text-muted d-flex flex-wrap gap-2">
                                                {urls.map(url => (
                                                    <a
                                                        key={url}
                                                        href={url}
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                        title={url}
                                                    >
                                                        {storeUrlLabel(url)}
                                                        <FontAwesomeIcon icon={faUpRightFromSquare} className="ms-1" />
                                                    </a>
                                                ))}
                                            </small>
                                        )}
                                    </div>
                                    <FontAwesomeIcon
                                        icon={faTrashCan}
                                        className="action-icon"
                                        title="Odebrat"
                                        onClick={() => handleRemove(s.name)}
                                        style={{ cursor: 'pointer' }}
                                    />
                                </ListGroup.Item>
                            );
                        })}
                    </ListGroup>
                )}
            </Modal.Body>
            <Modal.Footer>
                <Button variant="secondary" onClick={onClose}>Zavřít</Button>
            </Modal.Footer>
        </Modal>
    );
}
