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

export default function ServiceRecords() {
  const [records, setRecords] = useState([]);
  const [cars, setCars] = useState([]);
  const [services, setServices] = useState([]);
  const [form, setForm] = useState({ recordNumber: '', serviceDate: '', car: '', service: '' });

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

  const fetchData = async () => {
    try {
      const [rRes, cRes, sRes] = await Promise.all([
        axios.get('http://localhost:5000/api/servicerecord'),
        axios.get('http://localhost:5000/api/car'),
        axios.get('http://localhost:5000/api/service')
      ]);
      setRecords(rRes.data);
      setCars(cRes.data);
      setServices(sRes.data);
    } catch (err) {
      console.error("Error loading data:", err);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post('http://localhost:5000/api/servicerecord', form);
      setForm({ recordNumber: '', serviceDate: '', car: '', service: '' });
      fetchData();
    } catch (err) {
      alert("Failed to create record");
    }
  };

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-6">
      <h2 className="text-2xl font-black text-slate-800">Assign Car to Repair Service</h2>
      
      {/* Creation Form */}
      <form onSubmit={handleSubmit} className="bg-white p-6 rounded-2xl border border-slate-200 grid grid-cols-1 md:grid-cols-4 gap-4 shadow-sm">
        <input 
          className="border p-3 rounded-xl text-sm w-full font-bold text-black" 
          placeholder="Record Number (e.g. REC-001)" 
          value={form.recordNumber} 
          onChange={e => setForm({...form, recordNumber: e.target.value})} 
          required 
        />
        <input 
          className="border p-3 rounded-xl text-sm w-full font-bold text-black" 
          type="date" 
          value={form.serviceDate} 
          onChange={e => setForm({...form, serviceDate: e.target.value})} 
          required 
        />
        <select 
          className="border p-3 rounded-xl text-sm bg-white w-full font-bold text-black"
          value={form.car} 
          onChange={e => setForm({...form, car: e.target.value})} 
          required
        >
          <option value="">-- Select Target Car --</option>
          {cars.map(c => <option key={c._id} value={c._id}>{c.number} ({c.model})</option>)}
        </select>
        <select 
          className="border p-3 rounded-xl text-sm
           bg-white w-full font-bold text-black"
          value={form.service} 
          onChange={e => setForm({...form, service: e.target.value})} 
          required
        >
          <option value="" >-- Select Service Type --</option>
          {services.map(s => <option key={s._id} value={s._id}>{s.serviceName} ({s.servicePrice.toLocaleString()} RWF)</option>)}
        </select>
        <button type="submit" className="col-span-full bg-blue-600 text-white font-semibold py-3 rounded-xl hover:bg-blue-700 transition">
          Create Repair Assignment
        </button>
      </form>

      {/* Main Table */}
      <div className="bg-white border border-slate-200 
      rounded-2xl overflow-hidden shadow-sm">
        <table className="w-full text-left text-sm
         text-slate-600">
          <thead className="bg-slate-50 text-xs uppercase 
          font-bold text-slate-500 border-b border-slate-200">
            <tr>
              <th className="p-4">Record ID</th>
              <th className="p-4">Date</th>
              <th className="p-4">Car Plate</th>
              <th className="p-4">Service Action</th>
              <th className="p-4">Cost Estimate</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {records.map(r => (
              <tr key={r._id} className="hover:bg-slate-50">
                <td className="p-4 font-mono font-bold text-slate-900">{r.recordNumber}</td>
                <td className="p-4">{r.serviceDate ? new Date(r.serviceDate).toLocaleDateString() : 'N/A'}</td>
                <td className="p-4 text-blue-600 font-semibold">{r.car?.number || 'Deleted Car'}</td>
                <td className="p-4 font-medium">{r.service?.serviceName || 'Unknown Service'}</td>
                <td className="p-4 font-bold text-slate-900">{(r.service?.servicePrice || 0).toLocaleString()} RWF</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
