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

const Servicespage = () => {
  const [services, setServices] = useState([]);
  const [isEditing, setIsEditing] = useState(false);
  const [currentServiceId, setCurrentServiceId] = useState(null);
  const [formData, setFormData] = useState({
    serviceCode: '',
    servicename: '',
    price: ''
  });

  const fetchServices = async () => {
    try {
      const response = await api.get('/services/all');
      // Ensure we handle different possible response structures
      setServices(Array.isArray(response.data) ? response.data : response.data.services || []);
    } catch (error) {
      console.error("Error fetching services:", error);
    }
  };

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (isEditing) {
        // UPDATE: PUT request to the update endpoint
        await api.put(`/services/update/${currentServiceId}`, formData);
        alert("Service updated successfully!");
      } else {
        // ADD: POST request to the add endpoint
        await api.post('/services/add', formData);
        alert("Service added successfully!");
      }
      resetForm();
      fetchServices();
    } catch (error) {
      console.error("Submission error:", error);
      alert("Error processing request");
    }
  };

  const handleEdit = (service) => {
    setIsEditing(true);
    setCurrentServiceId(service._id);
    setFormData({
      serviceCode: service.serviceCode,
      servicename: service.servicename,
      price: service.price
    });
    // Smooth scroll to form for better UX
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id) => {
    if (window.confirm("Are you sure you want to delete this service?")) {
      try {
        await api.delete(`/services/delete/${id}`);
        fetchServices();
      } catch (error) {
        alert("Error deleting service");
      }
    }
  };

  const resetForm = () => {
    setIsEditing(false);
    setCurrentServiceId(null);
    setFormData({ serviceCode: '', servicename: '', price: '' });
  };

  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' }}>Manage Services</h2>
        <div style={{ fontSize: '14px', color: '#64748b' }}>Total Services: {services.length}</div>
      </div>

      {/* FORM SECTION */}
      <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 Details' : 'Register New Service'}
        </h3>
        <form onSubmit={handleSubmit} style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', 
          gap: '15px' 
        }}>
          <input 
            name="serviceCode" 
            placeholder="Service Code (e.g. S001)" 
            value={formData.serviceCode}
            onChange={handleChange} 
            style={inputStyle}
            required 
          />
          <input 
            name="servicename" 
            placeholder="Service Name" 
            value={formData.servicename}
            onChange={handleChange} 
            style={inputStyle}
            required 
          />
          <input 
            name="price" 
            type="number"
            placeholder="Price (RWF)" 
            value={formData.price}
            onChange={handleChange} 
            style={inputStyle}
            required 
          />
          <div style={{ display: 'flex', gap: '10px' }}>
            <button type="submit" style={buttonStyle}>
              {isEditing ? 'Save Changes' : 'Add Service'}
            </button>
            {isEditing && (
              <button type="button" onClick={resetForm} style={cancelButtonStyle}>
                Cancel
              </button>
            )}
          </div>
        </form>
      </div>

      {/* TABLE SECTION */}
      <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}>CODE</th>
              <th style={thStyle}>SERVICE NAME</th>
              <th style={thStyle}>PRICE</th>
              <th style={thStyle}>ACTION</th>
            </tr>
          </thead>
          <tbody>
            {services.length > 0 ? (
              services.map((s) => (
                <tr key={s._id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                  <td style={tdStyle}>
                    <span style={{ fontWeight: '600', color: '#2563eb' }}>{s.serviceCode}</span>
                  </td>
                  <td style={tdStyle}>{s.servicename}</td>
                  <td style={tdStyle}>{Number(s.price).toLocaleString()} RWF</td>
                  <td style={tdStyle}>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button onClick={() => handleEdit(s)} style={editButtonStyle}>
                        Edit
                      </button>
                      <button onClick={() => handleDelete(s._id)} style={deleteButtonStyle}>
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan="4" style={{ padding: '40px', textAlign: 'center', color: '#64748b' }}>
                  No services found. Add one above to get started.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// --- STYLES ---
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 Servicespage;