import React, { useEffect, useState } from 'react';
import api from '../axios';

const Carpage = () => {
  const [cars, setCars] = useState([]);
  const [isEditing, setIsEditing] = useState(false);
  const [currentCarId, setCurrentCarId] = useState(null);
  const [formData, setFormData] = useState({
    plateNumber: '',
    type: '',
    model: '',
    manufacturedDate: '',
    drivernumber: '',
    mechanicname: ''
  });

  const fetchCars = async () => {
    try {
      const response = await api.get('/cars/all');
      setCars(response.data);
    } catch (error) {
      console.error("Error fetching cars:", error);
    }
  };

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

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (isEditing) {
        // Edit existing car
        await api.put(`/cars/update/${currentCarId}`, formData);
        alert("Car updated successfully!");
      } else {
        // Add new car
        await api.post('/cars/add', formData);
        alert("Car added successfully!");
      }
      resetForm();
      fetchCars();
    } catch (error) {
      alert("Operation failed: " + error.response?.data?.message);
    }
  };

  const handleEdit = (car) => {
    setIsEditing(true);
    setCurrentCarId(car._id);
    // Format date for the input field (YYYY-MM-DD)
    const formattedDate = car.manufacturedDate ? car.manufacturedDate.split('T')[0] : '';
    setFormData({
      plateNumber: car.plateNumber,
      type: car.type,
      model: car.model,
      manufacturedDate: formattedDate,
      drivernumber: car.drivernumber,
      mechanicname: car.mechanicname
    });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id) => {
    if (window.confirm("Are you sure you want to delete this vehicle?")) {
      try {
        await api.delete(`/cars/delete/${id}`);
        fetchCars();
      } catch (error) {
        alert("Delete failed");
      }
    }
  };

  const resetForm = () => {
    setIsEditing(false);
    setCurrentCarId(null);
    setFormData({
      plateNumber: '',
      type: '',
      model: '',
      manufacturedDate: '',
      drivernumber: '',
      mechanicname: ''
    });
  };

  return (
    <div style={{ padding: '30px', backgroundColor: '#f8fafc', minHeight: '100vh' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '30px' }}>
        <h2 style={{ margin: 0, fontSize: '24px', fontWeight: '700', color: '#1e293b' }}>Vehicles Management</h2>
        <div style={{ fontSize: '14px', color: '#64748b' }}>Total Vehicles: {cars.length}</div>
      </div>

      <div style={{ 
        backgroundColor: '#fff', 
        padding: '25px', 
        borderRadius: '12px', 
        boxShadow: '0 1px 3px rgba(0,0,0,0.1)', 
        marginBottom: '30px' 
      }}>
        <h3 style={{ marginTop: 0, marginBottom: '20px', fontSize: '16px', color: '#334155' }}>
          {isEditing ? 'Edit Vehicle Details' : 'Register New Vehicle'}
        </h3>
        <form onSubmit={handleSubmit} style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', 
          gap: '15px' 
        }}>
          <input name="plateNumber" value={formData.plateNumber} placeholder="Plate Number" onChange={handleChange} style={inputStyle} required />
          <input name="type" value={formData.type} placeholder="Vehicle Type" onChange={handleChange} style={inputStyle} required />
          <input name="model" value={formData.model} placeholder="Model" onChange={handleChange} style={inputStyle} required />
          <input type="date" name="manufacturedDate" value={formData.manufacturedDate} onChange={handleChange} style={inputStyle} required />
          <input type="number" name="drivernumber" value={formData.drivernumber} placeholder="Driver Contact" onChange={handleChange} style={inputStyle} required />
          <input name="mechanicname" value={formData.mechanicname} placeholder="Assigned Mechanic" onChange={handleChange} style={inputStyle} required />
          <div style={{ display: 'flex', gap: '10px' }}>
            <button type="submit" style={buttonStyle}>{isEditing ? 'Update' : 'Add'} Vehicle</button>
            {isEditing && (
              <button type="button" onClick={resetForm} style={{ ...buttonStyle, backgroundColor: '#94a3b8' }}>Cancel</button>
            )}
          </div>
        </form>
      </div>

      <div style={{ backgroundColor: '#fff', borderRadius: '12px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)', overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left' }}>
          <thead>
            <tr style={{ backgroundColor: '#f1f5f9', borderBottom: '1px solid #e2e8f0' }}>
              <th style={thStyle}>PLATE NUMBER</th>
              <th style={thStyle}>VEHICLE MODEL</th>
              <th style={thStyle}>TYPE</th>
              <th style={thStyle}>MECHANIC</th>
              <th style={thStyle}>ACTIONS</th>
            </tr>
          </thead>
          <tbody>
            {cars.map((car) => (
              <tr key={car._id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                <td style={tdStyle}>
                  <span style={{ fontWeight: '600', color: '#2563eb' }}>{car.plateNumber}</span>
                </td>
                <td style={tdStyle}>{car.model}</td>
                <td style={tdStyle}>{car.type}</td>
                <td style={tdStyle}>{car.mechanicname}</td>
                <td style={tdStyle}>
                  <div style={{ display: 'flex', gap: '10px' }}>
                    <button 
                      onClick={() => handleEdit(car)}
                      style={actionButtonStyle("#eff6ff", "#2563eb")}
                    >
                      ✏️ Edit
                    </button>
                    <button 
                      onClick={() => handleDelete(car._id)}
                      style={actionButtonStyle("#fee2e2", "#dc2626")}
                    >
                      🗑️ Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// Reusable style helpers
const inputStyle = {
  padding: '12px',
  borderRadius: '8px',
  border: '1px solid #e2e8f0',
  fontSize: '14px',
  outline: 'none',
  backgroundColor: '#f8fafc'
};

const buttonStyle = {
  backgroundColor: '#2563eb',
  color: 'white',
  border: 'none',
  padding: '12px',
  borderRadius: '8px',
  fontWeight: '600',
  cursor: 'pointer'
};

const actionButtonStyle = (bg, color) => ({
  padding: '6px 12px',
  borderRadius: '6px',
  border: 'none',
  backgroundColor: bg,
  color: color,
  fontSize: '12px',
  fontWeight: '600',
  cursor: 'pointer'
});

const thStyle = { padding: '15px 20px', fontSize: '12px', color: '#64748b', textTransform: 'uppercase' };
const tdStyle = { padding: '15px 20px', fontSize: '14px', color: '#334155' };

export default Carpage;