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

const ServiceRecordpages = () => {
  const [records, setRecords] = useState([]);
  const [cars, setCars] = useState([]);
  const [services, setServices] = useState([]);
  
  // New states for Editing logic
  const [isEditing, setIsEditing] = useState(false);
  const [currentId, setCurrentId] = useState(null);

  const [formData, setFormData] = useState({
    serviceRecordCode: '',
    date: '',
    car: '',
    servicename: ''
  });

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

  const fetchData = async () => {
    try {
      const [recRes, carRes, serRes] = await Promise.all([
        api.get('/records/all'),
        api.get('/cars/all'),
        api.get('/services/all')
      ]);

      setRecords(Array.isArray(recRes.data) ? recRes.data : recRes.data.records || []);
      setCars(Array.isArray(carRes.data) ? carRes.data : carRes.data.cars || []);
      setServices(Array.isArray(serRes.data) ? serRes.data : serRes.data.services || []);
    } catch (err) {
      console.error("Fetch Error:", err);
      setRecords([]);
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (isEditing) {
        // UPDATE Logic
        await api.put(`/records/update/${currentId}`, formData);
        alert("Record updated successfully!");
      } else {
        // ADD Logic
        await api.post('/records/add', formData);
        alert("Record saved successfully!");
      }
      resetForm();
      fetchData();
    } catch (err) {
      const msg = err.response?.data?.message || "Error processing record";
      alert(msg);
    }
  };

  const handleEdit = (record) => {
    setIsEditing(true);
    setCurrentId(record._id);
    setFormData({
      serviceRecordCode: record.serviceRecordCode,
      // Format date to YYYY-MM-DD for the input field
      date: record.date ? new Date(record.date).toISOString().split('T')[0] : '',
      car: record.car?._id || '',
      servicename: record.servicename?._id || ''
    });
    // Scroll to form
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id) => {
    if (window.confirm("Are you sure you want to delete this record?")) {
      try {
        await api.delete(`/records/delete/${id}`);
        fetchData();
      } catch (err) {
        console.error("Delete Error:", err);
        alert("Error deleting record");
      }
    }
  };

  const resetForm = () => {
    setIsEditing(false);
    setCurrentId(null);
    setFormData({
      serviceRecordCode: '',
      date: '',
      car: '',
      servicename: ''
    });
  };

  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' }}>Service Records</h2>
        <div style={{ fontSize: '14px', color: '#64748b' }}>Total Records: {records.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 ? 'Update Service Entry' : 'Create Service Entry'}
        </h3>
        <form onSubmit={handleSubmit} style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', 
          gap: '15px' 
        }}>
          <input 
            name="serviceRecordCode" 
            placeholder="Record Code" 
            value={formData.serviceRecordCode} 
            onChange={handleChange} 
            style={inputStyle}
            required 
          />
          <input 
            name="date" 
            type="date" 
            value={formData.date} 
            onChange={handleChange} 
            style={inputStyle}
            required 
          />

          <select name="car" value={formData.car} onChange={handleChange} style={inputStyle} required>
            <option value="">Select Car</option>
            {Array.isArray(cars) && cars.map(c => (
              <option key={c._id} value={c._id}>{c.plateNumber}</option>
            ))}
          </select>

          <select name="servicename" value={formData.servicename} onChange={handleChange} style={inputStyle} required>
            <option value="">Select Service</option>
            {Array.isArray(services) && services.map(s => (
              <option key={s._id} value={s._id}>{s.servicename}</option>
            ))}
          </select>

          <div style={{ display: 'flex', gap: '10px' }}>
            <button type="submit" style={buttonStyle}>
              {isEditing ? 'Save Changes' : 'Save Record'}
            </button>
            {isEditing && (
              <button type="button" onClick={resetForm} style={cancelButtonStyle}>
                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}>RECORD CODE</th>
              <th style={thStyle}>DATE</th>
              <th style={thStyle}>VEHICLE</th>
              <th style={thStyle}>SERVICE</th>
              <th style={thStyle}>ACTIONS</th>
            </tr>
          </thead>
          <tbody>
            {Array.isArray(records) && records.length > 0 ? (
              records.map((r) => (
                <tr key={r._id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                  <td style={tdStyle}>
                    <span style={{ fontWeight: '600', color: '#2563eb' }}>{r.serviceRecordCode}</span>
                  </td>
                  <td style={tdStyle}>{new Date(r.date).toLocaleDateString()}</td>
                  <td style={tdStyle}>{r.car?.plateNumber || 'N/A'}</td>
                  <td style={tdStyle}>
                    <span style={{ padding: '4px 8px', backgroundColor: '#eff6ff', color: '#2563eb', borderRadius: '6px', fontSize: '12px' }}>
                      {r.servicename?.servicename || 'N/A'}
                    </span>
                  </td>
                  <td style={tdStyle}>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button 
                        onClick={() => handleEdit(r)}
                        style={editButtonStyle}
                      >
                        Edit
                      </button>
                      <button 
                        onClick={() => handleDelete(r._id)}
                        style={deleteButtonStyle}
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan="5" style={{ padding: '20px', textAlign: 'center', color: '#64748b' }}>No records found.</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

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 cancelButtonStyle = {
  backgroundColor: '#94a3b8',
  color: 'white',
  border: 'none',
  padding: '12px',
  borderRadius: '8px',
  fontWeight: '600',
  cursor: 'pointer'
};

const editButtonStyle = {
  backgroundColor: '#eff6ff',
  color: '#2563eb',
  border: 'none',
  padding: '6px 12px',
  borderRadius: '6px',
  fontSize: '12px',
  fontWeight: '600',
  cursor: 'pointer'
};

const deleteButtonStyle = {
  backgroundColor: '#fee2e2',
  color: '#dc2626',
  border: 'none',
  padding: '6px 12px',
  borderRadius: '6px',
  fontSize: '12px',
  fontWeight: '600',
  cursor: 'pointer'
};

const thStyle = {
  padding: '15px 20px',
  fontSize: '12px',
  color: '#64748b',
  textTransform: 'uppercase',
  letterSpacing: '0.05em'
};

const tdStyle = {
  padding: '15px 20px',
  fontSize: '14px',
  color: '#334155'
};

export default ServiceRecordpages;