import React, { useEffect, useState } from 'react';
import api from '../services/api';
import Modal from '../components/Modal';
import ConfirmDialog from '../components/ConfirmDialog';

const initialForm = {
  vehicle: '',
  serviceType: 'Routine',
  maintenanceCost: '',
  maintenanceDate: new Date().toISOString().slice(0, 10),
  vehicleStatus: 'Available',
};

const statusClasses = {
  Available: 'badge-success',
  'Under Maintenance': 'badge-warning',
  'Out Of Service': 'badge-danger',
};

export default function Maintenance() {
  const [records, setRecords] = useState([]);
  const [vehicles, setVehicles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [form, setForm] = useState(initialForm);
  const [editing, setEditing] = useState(false);
  const [message, setMessage] = useState('');

  const loadData = async () => {
    setLoading(true);
    try {
      const [maintenanceRes, vehiclesRes] = await Promise.all([api.get('/maintenance'), api.get('/vehicles')]);
      setRecords(maintenanceRes.data);
      setVehicles(vehiclesRes.data);
    } catch (err) {
      setMessage(err.response?.data?.message || 'Unable to load maintenance data');
    } finally {
      setLoading(false);
    }
  };

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

  const openAdd = () => {
    setForm(initialForm);
    setEditing(false);
    setSelectedId(null);
    setMessage('');
    setModalOpen(true);
  };

  const openEdit = (record) => {
    setForm({
      vehicle: record.vehicle?._id || record.vehicle,
      serviceType: record.serviceType,
      maintenanceCost: record.maintenanceCost,
      maintenanceDate: record.maintenanceDate?.slice(0, 10) || '',
      vehicleStatus: record.vehicleStatus,
    });
    setEditing(true);
    setSelectedId(record._id);
    setMessage('');
    setModalOpen(true);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setMessage('');
    if (!form.vehicle || !form.serviceType || form.maintenanceCost === '' || !form.maintenanceDate || !form.vehicleStatus) {
      setMessage('All maintenance fields are required.');
      return;
    }

    try {
      const payload = {
        vehicle: form.vehicle,
        serviceType: form.serviceType,
        maintenanceCost: Number(form.maintenanceCost),
        maintenanceDate: form.maintenanceDate,
        vehicleStatus: form.vehicleStatus,
      };

      if (editing) {
        await api.put(`/maintenance/${selectedId}`, payload);
      } else {
        await api.post('/maintenance', payload);
      }

      setModalOpen(false);
      loadData();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Unable to save maintenance record');
    }
  };

  return (
    <div className="space-y-6">
      <div className="page-header">
        <div>
          <h1 className="page-title">Maintenance Management</h1>
          <p className="text-sm text-gray-500">Create, edit, and delete maintenance records for vehicles.</p>
        </div>
        <button className="btn-primary" onClick={openAdd}>+ New Maintenance</button>
      </div>

      {message && <div className="rounded-lg bg-yellow-50 border border-yellow-100 p-4 text-sm text-yellow-700">{message}</div>}

      <div className="card overflow-x-auto">
        {loading ? (
          <div className="text-center py-10"><div className="animate-spin inline-block h-10 w-10 rounded-full border-b-2 border-blue-600"></div></div>
        ) : (
          <table className="w-full">
            <thead>
              <tr>
                <th className="table-header text-left">Vehicle</th>
                <th className="table-header text-left">Service Type</th>
                <th className="table-header text-left">Cost</th>
                <th className="table-header text-left">Date</th>
                <th className="table-header text-left">Status</th>
                <th className="table-header text-left">Actions</th>
              </tr>
            </thead>
            <tbody>
              {records.map((record) => (
                <tr key={record._id} className="table-row">
                  <td className="table-cell font-medium">{record.vehicle?.vehicleName || 'Unknown'}</td>
                  <td className="table-cell">{record.serviceType}</td>
                  <td className="table-cell">{Number(record.maintenanceCost).toLocaleString()}</td>
                  <td className="table-cell">{record.maintenanceDate?.slice(0, 10)}</td>
                  <td className="table-cell"><span className={statusClasses[record.vehicleStatus] || 'badge-gray'}>{record.vehicleStatus}</span></td>
                  <td className="table-cell">
                    <div className="flex gap-3">
                      <button onClick={() => openEdit(record)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">Edit</button>
                      <button onClick={() => { setSelectedId(record._id); setConfirmOpen(true); }} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                    </div>
                  </td>
                </tr>
              ))}
              {!records.length && (
                <tr>
                  <td colSpan={6} className="text-center py-10 text-gray-400">No maintenance records found.</td>
                </tr>
              )}
            </tbody>
          </table>
        )}
      </div>

      <Modal isOpen={modalOpen} onClose={() => setModalOpen(false)} title={editing ? 'Edit Maintenance' : 'Add Maintenance'} size="lg">
        <form onSubmit={handleSubmit} className="grid gap-4 md:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Vehicle</label>
            <select className="input-field" value={form.vehicle} onChange={(e) => setForm({ ...form, vehicle: e.target.value })} required>
              <option value="">Select a vehicle</option>
              {vehicles.map((vehicle) => (
                <option key={vehicle._id} value={vehicle._id}>
                  {vehicle.vehicleName} — {vehicle.plateNumber}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Service Type</label>
            <input className="input-field" value={form.serviceType} onChange={(e) => setForm({ ...form, serviceType: e.target.value })} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Maintenance Cost</label>
            <input type="number" className="input-field" value={form.maintenanceCost} onChange={(e) => setForm({ ...form, maintenanceCost: e.target.value })} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Maintenance Date</label>
            <input type="date" className="input-field" value={form.maintenanceDate} onChange={(e) => setForm({ ...form, maintenanceDate: e.target.value })} required />
          </div>
          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-gray-700 mb-1">Vehicle Status</label>
            <select className="input-field" value={form.vehicleStatus} onChange={(e) => setForm({ ...form, vehicleStatus: e.target.value })} required>
              <option>Available</option>
              <option>Under Maintenance</option>
              <option>Out Of Service</option>
            </select>
          </div>
          <div className="md:col-span-2 flex flex-col gap-3 pt-2 sm:flex-row sm:justify-end">
            <button type="button" className="btn-secondary w-full sm:w-auto" onClick={() => setModalOpen(false)}>
              Cancel
            </button>
            <button type="submit" className="btn-primary w-full sm:w-auto">
              {editing ? 'Update' : 'Save'}
            </button>
          </div>
        </form>
      </Modal>

      <ConfirmDialog isOpen={confirmOpen} onClose={() => setConfirmOpen(false)} onConfirm={async () => { await api.delete(`/maintenance/${selectedId}`); loadData(); }} />
    </div>
  );
}
