import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import offboardingService from '../services/offboardingService';
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: 'hardware_returned', label: 'Gesamte Hardware zurückgegeben' },
    { key: 'hardware_condition_good', label: 'Hardware in gutem Zustand' },
    { key: 'accounts_deactivated', label: 'Benutzerkonten deaktiviert' },
    { key: 'access_revoked', label: 'Zugriffsrechte entzogen' },
    { key: 'knowledge_transfer', label: 'Wissensübergabe abgeschlossen' },
    { key: 'final_clearance', label: 'Abschlussgespräch durchgeführt' }
];

const OffboardingPage = () => {
    const { isAdmin, isSuperAdmin } = useAuth();
    const [protocols, setProtocols] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [showReturnModal, setShowReturnModal] = useState(false);
    const [editingProtocol, setEditingProtocol] = useState(null);
    const [users, setUsers] = useState([]);
    const [assignedAssets, setAssignedAssets] = useState([]);
    const [assetReturns, setAssetReturns] = useState([]);
    const [formData, setFormData] = useState({
        employee_user_id: '',
        exit_date: new Date().toISOString().split('T')[0],
        status: 'pending',
        checklist_data: {},
        notes: ''
    });

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

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

            setProtocols(protocolsData);
            setUsers(usersData);
        } catch (error) {
            toast.error('Fehler beim Laden der Daten');
        } finally {
            setLoading(false);
        }
    };

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

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

    const handleReturnAssets = async (protocol) => {
        setEditingProtocol(protocol);

        try {
            const allAssets = await assetService.getAll();
            const userAssets = allAssets.filter(
                a => a.assigned_to_user_id === protocol.employee_user_id && a.status === 'zugewiesen'
            );

            setAssignedAssets(userAssets);
            setAssetReturns(userAssets.map(asset => ({
                asset_id: asset.id,
                condition: 'gut'
            })));
            setShowReturnModal(true);
        } catch (error) {
            toast.error('Fehler beim Laden der Assets');
        }
    };

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

        try {
            if (editingProtocol) {
                await offboardingService.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 offboardingService.create(formData);
                toast.success('Offboarding-Protokoll erfolgreich erstellt');
                setShowModal(false);

                // Direkt zur Asset-Rückgabe springen
                await loadData();
                const refreshedProtocol = await offboardingService.getById(newProtocol.id);
                handleReturnAssets(refreshedProtocol);
            }
        } catch (error) {
            toast.error(error.message || 'Fehler beim Speichern');
        }
    };

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

        try {
            await offboardingService.returnAssets(editingProtocol.id, assetReturns);
            toast.success('Assets erfolgreich zurückgegeben und PDF generiert');
            setShowReturnModal(false);
            loadData();
        } catch (error) {
            toast.error(error.message || 'Fehler beim Zurückgeben der Assets');
        }
    };

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

        try {
            await offboardingService.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 = offboardingService.downloadPdf(protocol.pdf_file_path);
            window.open(url, '_blank');
        } else {
            toast.warning('PDF noch nicht generiert');
        }
    };

    const updateAssetCondition = (assetId, condition) => {
        setAssetReturns(assetReturns.map(ar =>
            ar.asset_id === assetId ? { ...ar, condition } : ar
        ));
    };

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

        try {
            await offboardingService.update(editingProtocol.id, {
                status: 'completed',
                checklist_data: formData.checklist_data,
                notes: formData.notes,
                completion_date: new Date().toISOString().split('T')[0]
            });
            toast.success('Offboarding 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>Offboarding</h1>
                    {(isAdmin() || isSuperAdmin()) && (
                        <button onClick={handleCreate} className="btn btn-primary">
                            + Neues Offboarding
                        </button>
                    )}
                </div>

                <div className="card">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>Mitarbeiter</th>
                                <th>Austrittsdatum</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 Offboarding-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.exit_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={() => handleReturnAssets(protocol)}
                                                    className="btn btn-warning btn-small"
                                                >
                                                    Assets zurück
                                                </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 Offboarding</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">Austrittsdatum*</label>
                                    <input
                                        type="date"
                                        className="form-input"
                                        value={formData.exit_date}
                                        onChange={(e) =>
                                            setFormData({ ...formData, exit_date: e.target.value })
                                        }
                                        required
                                    />
                                </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">Offboarding 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"
                                        >
                                            ✓ Offboarding abschließen
                                        </button>
                                    )}
                                </div>
                            </form>
                        </div>
                    </div>
                )}

                {/* Return Assets Modal */}
                {showReturnModal && (
                    <div className="modal-overlay" onClick={() => setShowReturnModal(false)}>
                        <div className="modal-content modal-large" onClick={(e) => e.stopPropagation()}>
                            <div className="modal-header">
                                <h2 className="modal-title">Assets zurückgeben</h2>
                                <button className="modal-close" onClick={() => setShowReturnModal(false)}>
                                    ×
                                </button>
                            </div>

                            <form onSubmit={handleSubmitReturn}>
                                <div className="form-group">
                                    <label className="form-label">Zugewiesene Assets</label>
                                    {assignedAssets.length === 0 ? (
                                        <p className="text-muted">Keine Assets zugewiesen</p>
                                    ) : (
                                        <table className="table">
                                            <thead>
                                                <tr>
                                                    <th>Typ</th>
                                                    <th>Name</th>
                                                    <th>Seriennummer</th>
                                                    <th>Zustand</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {assignedAssets.map((asset) => (
                                                    <tr key={asset.id}>
                                                        <td>{asset.type}</td>
                                                        <td>{asset.name}</td>
                                                        <td>{asset.serial_number}</td>
                                                        <td>
                                                            <select
                                                                className="form-select"
                                                                value={assetReturns.find(ar => ar.asset_id === asset.id)?.condition || 'gut'}
                                                                onChange={(e) => updateAssetCondition(asset.id, e.target.value)}
                                                            >
                                                                <option value="gut">Gut</option>
                                                                <option value="beschaedigt">Beschädigt</option>
                                                            </select>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    )}
                                </div>

                                <div className="card-footer">
                                    <button
                                        type="button"
                                        onClick={() => setShowReturnModal(false)}
                                        className="btn btn-secondary"
                                    >
                                        Abbrechen
                                    </button>
                                    <button type="submit" className="btn btn-primary">
                                        Assets zurückgeben & PDF erstellen
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default OffboardingPage;
