import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import onboardingService from '../services/onboardingService';
import userService from '../services/userService';
import assetService from '../services/assetService';
import LoadingSpinner from '../components/common/LoadingSpinner';
import ChecklistEditor from '../components/common/ChecklistEditor';
import { toast } from 'react-toastify';

const CHECKLIST_ITEMS = [
    { key: 'account_created', label: 'Benutzerkonto erstellt' },
    { key: 'email_configured', label: 'E-Mail-Konto konfiguriert' },
    { key: 'hardware_assigned', label: 'Hardware zugewiesen' },
    { key: 'software_installed', label: 'Software installiert' },
    { key: 'training_completed', label: 'Einarbeitungsschulung abgeschlossen' },
    { key: 'security_briefing', label: 'Sicherheitseinweisung durchgeführt' },
    { key: 'workspace_setup', label: 'Arbeitsplatz eingerichtet' }
];

const OnboardingPage = () => {
    const { isAdmin, isSuperAdmin } = useAuth();
    const [protocols, setProtocols] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [editingProtocol, setEditingProtocol] = useState(null);
    const [users, setUsers] = useState([]);
    const [assets, setAssets] = useState([]);
    const [formData, setFormData] = useState({
        employee_user_id: '',
        start_date: new Date().toISOString().split('T')[0],
        status: 'pending',
        checklist_data: {},
        notes: '',
        asset_ids: []
    });

    useEffect(() => {
        loadData();
    }, []);

    const loadData = async () => {
        try {
            const [protocolsData, usersData, assetsData] = await Promise.all([
                onboardingService.getAll(),
                userService.getAll(),
                assetService.getAll()
            ]);

            setProtocols(protocolsData);
            setUsers(usersData.filter(u => u.is_active));
            setAssets(assetsData.filter(a => a.status === 'verfuegbar'));
        } catch (error) {
            toast.error('Fehler beim Laden der Daten');
        } finally {
            setLoading(false);
        }
    };

    const handleCreate = () => {
        setEditingProtocol(null);
        setFormData({
            employee_user_id: '',
            start_date: new Date().toISOString().split('T')[0],
            status: 'pending',
            checklist_data: {},
            notes: '',
            asset_ids: []
        });
        setShowModal(true);
    };

    const handleEdit = (protocol) => {
        setEditingProtocol(protocol);
        setFormData({
            employee_user_id: protocol.employee_user_id,
            start_date: protocol.start_date,
            status: protocol.status,
            checklist_data: protocol.checklist_data ? JSON.parse(protocol.checklist_data) : {},
            notes: protocol.notes || '',
            asset_ids: []
        });
        setShowDetailModal(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        try {
            if (editingProtocol) {
                await onboardingService.update(editingProtocol.id, {
                    status: formData.status,
                    checklist_data: formData.checklist_data,
                    notes: formData.notes
                });
                toast.success('Protokoll erfolgreich aktualisiert');
                setShowModal(false);
                setShowDetailModal(false);
                loadData();
            } else {
                const newProtocol = await onboardingService.create(formData);
                toast.success('Onboarding-Protokoll erfolgreich erstellt');
                setShowModal(false);

                // Direkt zur Checklist springen
                await loadData();
                const refreshedProtocol = await onboardingService.getById(newProtocol.id);
                handleEdit(refreshedProtocol);
            }
        } catch (error) {
            toast.error(error.message || 'Fehler beim Speichern');
        }
    };

    const handleDelete = async (id) => {
        if (!window.confirm('Möchten Sie dieses Protokoll wirklich löschen?')) {
            return;
        }

        try {
            await onboardingService.delete(id);
            toast.success('Protokoll erfolgreich gelöscht');
            loadData();
        } catch (error) {
            toast.error(error.message || 'Fehler beim Löschen');
        }
    };

    const handleDownloadPdf = (protocol) => {
        if (protocol.pdf_file_path) {
            const url = onboardingService.downloadPdf(protocol.pdf_file_path);
            window.open(url, '_blank');
        } else {
            toast.warning('PDF noch nicht generiert');
        }
    };

    const handleRegeneratePdf = async (id) => {
        try {
            await onboardingService.regeneratePdf(id);
            toast.success('PDF erfolgreich neu generiert');
            loadData();
        } catch (error) {
            toast.error('Fehler beim Generieren des PDFs');
        }
    };

    const handleComplete = async () => {
        if (!editingProtocol) return;

        try {
            await onboardingService.update(editingProtocol.id, {
                status: 'completed',
                checklist_data: formData.checklist_data,
                notes: formData.notes,
                completion_date: new Date().toISOString().split('T')[0]
            });
            toast.success('Onboarding erfolgreich abgeschlossen!');
            setShowDetailModal(false);
            loadData();
        } catch (error) {
            toast.error('Fehler beim Abschließen');
        }
    };

    const getStatusBadgeClass = (status) => {
        const classes = {
            pending: 'status-pending',
            in_progress: 'status-in_progress',
            completed: 'status-completed'
        };
        return classes[status] || '';
    };

    const getStatusLabel = (status) => {
        const labels = {
            pending: 'Ausstehend',
            in_progress: 'In Bearbeitung',
            completed: 'Abgeschlossen'
        };
        return labels[status] || status;
    };

    if (loading) {
        return (
            <div className="main-content">
                <LoadingSpinner />
            </div>
        );
    }

    return (
        <div className="main-content">
            <div className="container">
                <div className="flex justify-between items-center mb-3">
                    <h1>Onboarding</h1>
                    {(isAdmin() || isSuperAdmin()) && (
                        <button onClick={handleCreate} className="btn btn-primary">
                            + Neues Onboarding
                        </button>
                    )}
                </div>

                <div className="card">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>Mitarbeiter</th>
                                <th>Startdatum</th>
                                <th>Status</th>
                                <th>PDF</th>
                                <th>Erstellt von</th>
                                <th>Aktionen</th>
                            </tr>
                        </thead>
                        <tbody>
                            {protocols.length === 0 ? (
                                <tr>
                                    <td colSpan="6" className="text-center">
                                        Keine Onboarding-Protokolle gefunden
                                    </td>
                                </tr>
                            ) : (
                                protocols.map((protocol) => (
                                    <tr key={protocol.id}>
                                        <td>
                                            {protocol.employee_first_name} {protocol.employee_last_name}
                                            <br />
                                            <small className="text-muted">{protocol.employee_email}</small>
                                        </td>
                                        <td>{new Date(protocol.start_date).toLocaleDateString('de-DE')}</td>
                                        <td>
                                            <span className={`status-badge ${getStatusBadgeClass(protocol.status)}`}>
                                                {getStatusLabel(protocol.status)}
                                            </span>
                                        </td>
                                        <td>
                                            {protocol.pdf_file_path ? (
                                                <button
                                                    onClick={() => handleDownloadPdf(protocol)}
                                                    className="btn btn-success btn-small"
                                                >
                                                    📄 Download
                                                </button>
                                            ) : (
                                                <span className="text-muted">Nicht verfügbar</span>
                                            )}
                                        </td>
                                        <td>{protocol.created_by_username}</td>
                                        <td>
                                            <div className="table-actions">
                                                <button
                                                    onClick={() => handleEdit(protocol)}
                                                    className="btn btn-primary btn-small"
                                                >
                                                    Bearbeiten
                                                </button>
                                                <button
                                                    onClick={() => handleRegeneratePdf(protocol.id)}
                                                    className="btn btn-secondary btn-small"
                                                >
                                                    PDF neu
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(protocol.id)}
                                                    className="btn btn-danger btn-small"
                                                >
                                                    Löschen
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>

                {/* Create Modal */}
                {showModal && (
                    <div className="modal-overlay" onClick={() => setShowModal(false)}>
                        <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                            <div className="modal-header">
                                <h2 className="modal-title">Neues Onboarding</h2>
                                <button className="modal-close" onClick={() => setShowModal(false)}>
                                    ×
                                </button>
                            </div>

                            <form onSubmit={handleSubmit}>
                                <div className="form-group">
                                    <label className="form-label">Mitarbeiter*</label>
                                    <select
                                        className="form-select"
                                        value={formData.employee_user_id}
                                        onChange={(e) =>
                                            setFormData({ ...formData, employee_user_id: e.target.value })
                                        }
                                        required
                                    >
                                        <option value="">-- Bitte wählen --</option>
                                        {users.map((user) => (
                                            <option key={user.id} value={user.id}>
                                                {user.first_name} {user.last_name} ({user.username})
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Startdatum*</label>
                                    <input
                                        type="date"
                                        className="form-input"
                                        value={formData.start_date}
                                        onChange={(e) =>
                                            setFormData({ ...formData, start_date: e.target.value })
                                        }
                                        required
                                    />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Assets zuweisen</label>
                                    <select
                                        multiple
                                        className="form-select"
                                        value={formData.asset_ids}
                                        onChange={(e) =>
                                            setFormData({
                                                ...formData,
                                                asset_ids: Array.from(e.target.selectedOptions, option => option.value)
                                            })
                                        }
                                        style={{ minHeight: '120px' }}
                                    >
                                        {assets.map((asset) => (
                                            <option key={asset.id} value={asset.id}>
                                                {asset.type} - {asset.name} ({asset.serial_number})
                                            </option>
                                        ))}
                                    </select>
                                    <small className="text-muted">Strg/Cmd gedrückt halten für Mehrfachauswahl</small>
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Notizen</label>
                                    <textarea
                                        className="form-textarea"
                                        rows="3"
                                        value={formData.notes}
                                        onChange={(e) =>
                                            setFormData({ ...formData, notes: e.target.value })
                                        }
                                    />
                                </div>

                                <div className="card-footer">
                                    <button
                                        type="button"
                                        onClick={() => setShowModal(false)}
                                        className="btn btn-secondary"
                                    >
                                        Abbrechen
                                    </button>
                                    <button type="submit" className="btn btn-primary">
                                        Erstellen
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}

                {/* Detail/Edit Modal */}
                {showDetailModal && editingProtocol && (
                    <div className="modal-overlay" onClick={() => setShowDetailModal(false)}>
                        <div className="modal-content modal-large" onClick={(e) => e.stopPropagation()}>
                            <div className="modal-header">
                                <h2 className="modal-title">Onboarding bearbeiten</h2>
                                <button className="modal-close" onClick={() => setShowDetailModal(false)}>
                                    ×
                                </button>
                            </div>

                            <form onSubmit={handleSubmit}>
                                <div className="form-group">
                                    <label className="form-label">Mitarbeiter</label>
                                    <input
                                        type="text"
                                        className="form-input"
                                        value={`${editingProtocol.employee_first_name} ${editingProtocol.employee_last_name}`}
                                        disabled
                                    />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Status*</label>
                                    <select
                                        className="form-select"
                                        value={formData.status}
                                        onChange={(e) =>
                                            setFormData({ ...formData, status: e.target.value })
                                        }
                                        required
                                    >
                                        <option value="pending">Ausstehend</option>
                                        <option value="in_progress">In Bearbeitung</option>
                                        <option value="completed">Abgeschlossen</option>
                                    </select>
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Checkliste</label>
                                    <ChecklistEditor
                                        items={CHECKLIST_ITEMS}
                                        checkedItems={formData.checklist_data}
                                        onChange={(checkedItems) =>
                                            setFormData({ ...formData, checklist_data: checkedItems })
                                        }
                                    />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Notizen</label>
                                    <textarea
                                        className="form-textarea"
                                        rows="4"
                                        value={formData.notes}
                                        onChange={(e) =>
                                            setFormData({ ...formData, notes: e.target.value })
                                        }
                                    />
                                </div>

                                <div className="card-footer">
                                    <button
                                        type="button"
                                        onClick={() => setShowDetailModal(false)}
                                        className="btn btn-secondary"
                                    >
                                        Abbrechen
                                    </button>
                                    <button type="submit" className="btn btn-primary">
                                        Speichern
                                    </button>
                                    {formData.status !== 'completed' && (
                                        <button
                                            type="button"
                                            onClick={handleComplete}
                                            className="btn btn-success"
                                        >
                                            ✓ Onboarding abschließen
                                        </button>
                                    )}
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default OnboardingPage;
