import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Button, Table, Alert } from 'react-bootstrap';
import NewMaintenanceForm from './NewMaintenanceForm';
import axios from 'axios';

const JorgeDashboard = () => {
    const [maintenanceHistory, setMaintenanceHistory] = useState([]);
    const [pendingAlerts, setPendingAlerts] = useState([]);
    const [showNewMaintenanceForm, setShowNewMaintenanceForm] = useState(false);
    const [vehicles, setVehicles] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

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

    const fetchData = async () => {
        try {
            setLoading(true);
            const [historyRes, alertsRes, vehiclesRes] = await Promise.all([
                axios.get('/api/maintenance/history'),
                axios.get('/api/maintenance/alerts'),
                axios.get('/api/maintenance/vehicles')
            ]);

            setMaintenanceHistory(historyRes.data);
            setPendingAlerts(alertsRes.data);
            setVehicles(vehiclesRes.data);
            setError(null);
        } catch (err) {
            setError('Error al cargar los datos. Por favor, intente nuevamente.');
            console.error('Error fetching data:', err);
        } finally {
            setLoading(false);
        }
    };

    const handleNewMaintenance = async (formData) => {
        try {
            const response = await axios.post('/api/maintenance', formData);
            setMaintenanceHistory(prev => [response.data.maintenance, ...prev]);
            setShowNewMaintenanceForm(false);
        } catch (err) {
            setError('Error al guardar el mantenimiento. Por favor, intente nuevamente.');
            console.error('Error saving maintenance:', err);
        }
    };

    if (loading) {
        return <div className="text-center p-5">Cargando...</div>;
    }

    if (error) {
        return <Alert variant="danger">{error}</Alert>;
    }

    return (
        <div className="container-fluid">
            <h2 className="mb-4">Panel de Control - Mantenimiento de Vehículos</h2>

            {/* Alertas Pendientes */}
            <Row className="mb-4">
                <Col>
                    <Card>
                        <Card.Header>
                            <h4>Alertas de Mantenimiento Pendiente</h4>
                        </Card.Header>
                        <Card.Body>
                            {pendingAlerts.length === 0 ? (
                                <Alert variant="success">No hay alertas pendientes</Alert>
                            ) : (
                                pendingAlerts.map(alert => (
                                    <Alert key={alert.id} variant="warning">
                                        <strong>{alert.vehicle.plate}</strong> - {alert.maintenance_type} pendiente para: {new Date(alert.next_maintenance_date).toLocaleDateString()}
                                    </Alert>
                                ))
                            )}
                        </Card.Body>
                    </Card>
                </Col>
            </Row>

            {/* Historial de Mantenimientos */}
            <Row>
                <Col>
                    <Card>
                        <Card.Header className="d-flex justify-content-between align-items-center">
                            <h4>Historial de Mantenimientos</h4>
                            <Button
                                variant="primary"
                                onClick={() => setShowNewMaintenanceForm(true)}
                            >
                                Nuevo Mantenimiento
                            </Button>
                        </Card.Header>
                        <Card.Body>
                            <Table striped bordered hover>
                                <thead>
                                    <tr>
                                        <th>Vehículo</th>
                                        <th>Fecha</th>
                                        <th>Tipo</th>
                                        <th>Estado</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {maintenanceHistory.map(record => (
                                        <tr key={record.id}>
                                            <td>{record.vehicle.plate}</td>
                                            <td>{new Date(record.date).toLocaleDateString()}</td>
                                            <td>{record.maintenance_type}</td>
                                            <td>{record.status}</td>
                                            <td>
                                                <Button variant="info" size="sm" className="me-2">
                                                    Ver Detalles
                                                </Button>
                                                <Button variant="secondary" size="sm">
                                                    Editar
                                                </Button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </Table>
                        </Card.Body>
                    </Card>
                </Col>
            </Row>

            {/* Modal de Nuevo Mantenimiento */}
            <NewMaintenanceForm
                show={showNewMaintenanceForm}
                handleClose={() => setShowNewMaintenanceForm(false)}
                onSubmit={handleNewMaintenance}
                vehicles={vehicles}
            />
        </div>
    );
};

export default JorgeDashboard;
