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

const Paymentpage = () => {
  const [payments, setPayments] = useState([]);
  const [records, setRecords] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [currentId, setCurrentId] = useState(null);

  const [formData, setFormData] = useState({
    paymentCode: '',
    amount: '',
    date: '',
    serviceRecordcode: ''
  });

  const fetchData = async () => {
    try {
      setLoading(true);
      const [payRes, recRes] = await Promise.all([
        api.get('/payments/all'),
        api.get('/records/all')
      ]);

      setPayments(payRes.data?.payments || payRes.data || []);
      const recData = recRes.data?.records || recRes.data?.result || recRes.data || [];
      setRecords(recData);
    } catch (error) {
      console.error("Fetch Error:", error);
    } finally {
      setLoading(false);
    }
  };

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

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

  const resetForm = () => {
    setFormData({ paymentCode: '', amount: '', date: '', serviceRecordcode: '' });
    setIsEditing(false);
    setCurrentId(null);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (isEditing) {
        await api.put(`/payments/update/${currentId}`, formData);
        alert("Payment updated!");
      } else {
        await api.post('/payments/add', formData);
        alert("Payment recorded (Report auto-generated)!");
      }
      resetForm();
      fetchData();
    } catch (error) {
      alert(error.response?.data?.message || "Error saving payment");
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm("Delete this payment?")) return;
    try {
      await api.delete(`/payments/delete/${id}`);
      fetchData();
    } catch (error) {
      alert("Delete failed");
    }
  };

  const handleEdit = (p) => {
    setIsEditing(true);
    setCurrentId(p._id);
    setFormData({
      paymentCode: p.paymentCode || '',
      amount: p.amount || '',
      date: p.date ? new Date(p.date).toISOString().split('T')[0] : '',
      serviceRecordcode: p.serviceRecordcode?._id || ''
    });
  };


  const containerStyle = { padding: '40px', background: '#f1f5f9', minHeight: '100vh', fontFamily: 'Inter, sans-serif' };
  const cardStyle = { background: 'white', padding: '30px', borderRadius: '12px', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)', marginBottom: '30px' };
  const inputStyle = { padding: '12px', borderRadius: '8px', border: '1px solid #e2e8f0', fontSize: '14px', width: '100%' };
  const btnPrimary = { padding: '12px 24px', background: '#2563eb', color: 'white', border: 'none', borderRadius: '8px', fontWeight: '600', cursor: 'pointer' };
  const btnSecondary = { padding: '12px 24px', background: '#64748b', color: 'white', border: 'none', borderRadius: '8px', fontWeight: '600', cursor: 'pointer', marginLeft: '10px' };
  const thStyle = { textAlign: 'left', padding: '15px', borderBottom: '2px solid #f1f5f9', color: '#64748b', fontSize: '13px', textTransform: 'uppercase', letterSpacing: '0.05em' };
  const tdStyle = { padding: '15px', borderBottom: '1px solid #f1f5f9', fontSize: '14px', color: '#1e293b' };

  return (
    <div style={containerStyle}>
      <h2 style={{ marginBottom: '25px', color: '#0f172a', fontWeight: '700' }}>Payments & Billing</h2>

     
      <div style={cardStyle}>
        <h4 style={{ marginBottom: '20px', color: '#475569' }}>{isEditing ? "Edit Payment" : "New Payment"}</h4>
        <form onSubmit={handleSubmit} style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '15px', alignItems: 'end' }}>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', fontSize: '12px', color: '#64748b' }}>Payment Code</label>
            <input name="paymentCode" style={inputStyle} placeholder="P001" value={formData.paymentCode} onChange={handleChange} required />
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', fontSize: '12px', color: '#64748b' }}>Amount (RWF)</label>
            <input name="amount" type="number" style={inputStyle} placeholder="0.00" value={formData.amount} onChange={handleChange} required />
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', fontSize: '12px', color: '#64748b' }}>Date</label>
            <input name="date" type="date" style={inputStyle} value={formData.date} onChange={handleChange} required />
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '5px', fontSize: '12px', color: '#64748b' }}>Service Record</label>
            <select name="serviceRecordcode" style={inputStyle} value={formData.serviceRecordcode} onChange={handleChange} required>
              <option value="">- Select Record & Car -</option>
              {records?.map((rec) => (
                <option key={rec._id} value={rec._id}>
                  {rec.serviceRecordCode || rec.serviceRecordcode} — {rec.car?.plateNumber || "Unknown"}
                </option>
              ))}
            </select>
          </div>
          <div style={{ display: 'flex' }}>
            <button type="submit" style={btnPrimary}>
              {isEditing ? "Update" : "Submit Payment"}
            </button>
            {isEditing && <button type="button" onClick={resetForm} style={btnSecondary}>Cancel</button>}
          </div>
        </form>
      </div>

     
      <div style={cardStyle}>
        {loading ? (
          <p style={{ textAlign: 'center', color: '#64748b' }}>Loading transactions...</p>
        ) : (
          <table width="100%" style={{ borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={thStyle}>Payment Code</th>
                <th style={thStyle}>Record (Car)</th>
                <th style={thStyle}>Amount</th>
                <th style={thStyle}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {payments.map((p) => (
                <tr key={p._id} style={{ transition: 'background 0.2s' }} onMouseOver={(e) => e.currentTarget.style.background = '#f8fafc'} onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}>
                  <td style={tdStyle}>{p.paymentCode}</td>
                  <td style={tdStyle}>
                    <span style={{ fontWeight: '600', color: '#2563eb' }}>{p.serviceRecordcode?.serviceRecordCode || 'N/A'}</span> 
                    <span style={{ color: '#94a3b8', marginLeft: '8px' }}>({p.serviceRecordcode?.car?.plateNumber || 'No Car'})</span>
                  </td>
                  <td style={tdStyle}>{p.amount?.toLocaleString()} RWF</td>
                  <td style={tdStyle}>
                    <button onClick={() => handleEdit(p)} style={{ background: 'none', border: 'none', color: '#2563eb', cursor: 'pointer', marginRight: '15px', fontWeight: '600' }}>Edit</button>
                    <button onClick={() => handleDelete(p._id)} style={{ background: 'none', border: 'none', color: '#ef4444', cursor: 'pointer', fontWeight: '600' }}>Delete</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};

export default Paymentpage;