import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { AuthService, VehicleRepairService, VehicleService } from "../../services";
import { Upload, Trash } from "react-bootstrap-icons";
import { Breadcrumb } from "react-bootstrap";
import DatePicker from "react-datepicker";
import moment from "moment";
import {
  REPAIR_PART_NAME,
  REPAIR_PART_NAME_TEXT,
  QUANTITY_OPTIONS
} from "../../shared";

const AddRepairRecord = () => {
  const navigate = useNavigate();
  const params = useParams();

  const [currentVehicle, setCurrentVehicle] = useState(null);
  const [existingRepairs, setExistingRepairs] = useState([]);

  const [partName, setPartName] = useState('');
  const [partNameOther, setPartNameOther] = useState('');
  const [replacementDate, setReplacementDate] = useState(null);
  const [mileage, setMileage] = useState('');
  const [quantity, setQuantity] = useState('');
  const [cost, setCost] = useState('');
  const [location, setLocation] = useState('');
  const [receiptFile, setReceiptFile] = useState(null);
  const [nextReminder, setNextReminder] = useState('');

  useEffect(() => {
    if (!AuthService.canAddOrEditVechiles()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page.');
      AuthService.logout();
      navigate('/login');
    }
    VehicleService.getVehicle(params.id).then((data) => {
      setCurrentVehicle(data.data);
    });
  }, []);

  useEffect(() => {
    if (currentVehicle) {
      fetchRepairs();
    }
  }, [currentVehicle]);

  const fetchRepairs = () => {
    VehicleRepairService.getAll(currentVehicle.id)
      .then(res => setExistingRepairs(res.data || []))
      .catch(() => setExistingRepairs([]));
  };

  const formatDateForBackend = (date) => {
    if (!date) return '';
    return moment(date).format('MM/DD/YYYY');
  };

  const handleSave = () => {
    if (!partName) {
      window.alert('Please select a part name.');
      return;
    }
    if (partName === REPAIR_PART_NAME.OTHER && !partNameOther.trim()) {
      window.alert('Please specify Other Parts.');
      return;
    }
    const data = {
      vehicle: currentVehicle?.id,
      part_name: partName,
      part_name_other: partName === REPAIR_PART_NAME.OTHER ? partNameOther.trim() : '',
      repair_date: formatDateForBackend(replacementDate),
      mileage_at_replacement: mileage,
      quantity,
      repair_price: cost,
      repair_location: location,
      next_replacement_reminder: nextReminder
    };
    VehicleRepairService.createNewVehicleRepair(data).then(result => {
      const record = result.data;
      const uploadPromise = receiptFile
        ? VehicleService.uploadVechileFile(
            (() => { const fd = new FormData(); fd.append('file', receiptFile); return fd; })(),
            currentVehicle.id, record.id, 'repair', replacementDate || new Date()
          )
        : Promise.resolve();
      uploadPromise.then(() => {
        setPartName('');
        setPartNameOther('');
        setReplacementDate(null);
        setMileage('');
        setQuantity('');
        setCost('');
        setLocation('');
        setReceiptFile(null);
        setNextReminder('');
        fetchRepairs();
      });
    });
  };

  const deleteRepair = (repairId) => {
    if (window.confirm('Are you sure you want to delete this repair record?')) {
      VehicleRepairService.deleteVehicleRepair(repairId).then(() => fetchRepairs());
    }
  };

  const goBack = () => {
    navigate(`/vehicles/${params.id}?tab=documents`);
  };

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/trans-routes/dashboard">Transportation</Breadcrumb.Item>
          <Breadcrumb.Item href="/vehicles/list">Vehicles Information</Breadcrumb.Item>
          <Breadcrumb.Item href={`/vehicles/${params.id}?tab=documents`}>View Vehicle Information</Breadcrumb.Item>
          <Breadcrumb.Item active>Add Repair Record</Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>Add Repair Record <button className="btn btn-link btn-sm" onClick={goBack}>Back</button></h4>
        </div>
      </div>
      <div className="app-main-content-list-container form-page">
        <div className="app-main-content-list-func-container">
          <h6 className="text-primary">Repair & Maintenance Record</h6>

          {existingRepairs.length > 0 && (
            <>
              <div className="field-label mb-2">Existing Records</div>
              <table className="table table-sm table-bordered mb-4">
                <thead>
                  <tr>
                    <th>Part Name</th>
                    <th>Date</th>
                    <th>Mileage</th>
                    <th>Qty</th>
                    <th>Cost</th>
                    <th>Location</th>
                    <th>Next Reminder</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  {existingRepairs.map((repair) => (
                    <tr key={repair.id}>
                      <td>
                        {repair.part_name === REPAIR_PART_NAME.OTHER
                          ? (repair.part_name_other || REPAIR_PART_NAME_TEXT[repair.part_name] || '-')
                          : (REPAIR_PART_NAME_TEXT[repair.part_name] || repair.repair_description || repair.part_name || '-')}
                      </td>
                      <td>{repair.repair_date || '-'}</td>
                      <td>{repair.mileage_at_replacement || '-'}</td>
                      <td>{repair.quantity || '-'}</td>
                      <td>{repair.repair_price || '-'}</td>
                      <td>{repair.repair_location || '-'}</td>
                      <td>{repair.next_replacement_reminder || '-'}</td>
                      <td>
                        <button className="btn btn-link btn-sm p-0 text-danger" onClick={() => deleteRepair(repair.id)}>
                          <Trash size={14} />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}

          <div className="field-label mb-2">Add New Record</div>
          <div className="app-main-content-fields-section">
            <div className="me-4">
              <div className="field-label">Part Name</div>
              <select value={partName} onChange={e => setPartName(e.target.value)}>
                <option value="">Select...</option>
                {Object.keys(REPAIR_PART_NAME).map(key => (
                  <option key={key} value={REPAIR_PART_NAME[key]}>{REPAIR_PART_NAME_TEXT[REPAIR_PART_NAME[key]]}</option>
                ))}
              </select>
            </div>
            {partName === REPAIR_PART_NAME.OTHER && (
              <div className="me-4">
                <div className="field-label">Other Parts-Please Specify</div>
                <input
                  type="text"
                  placeholder="e.g., Door handle bracket"
                  value={partNameOther}
                  onChange={e => setPartNameOther(e.target.value)}
                />
              </div>
            )}
            <div className="me-4">
              <div className="field-label">Replacement Date</div>
              <DatePicker
                selected={replacementDate}
                onChange={(date) => setReplacementDate(date)}
                dateFormat="MM/dd/yyyy"
                placeholderText="e.g., 03/01/2024"
                className="form-control"
              />
            </div>
            <div className="me-4">
              <div className="field-label">Mileage at Replacement</div>
              <input type="text" placeholder="e.g., 48,000" value={mileage} onChange={e => setMileage(e.target.value)} />
            </div>
            <div className="me-4">
              <div className="field-label">Quantity</div>
              <select value={quantity} onChange={e => setQuantity(e.target.value)}>
                <option value="">Select...</option>
                {QUANTITY_OPTIONS.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>
          </div>
          <div className="app-main-content-fields-section">
            <div className="me-4">
              <div className="field-label">Cost</div>
              <input type="text" placeholder="e.g., $250.00" value={cost} onChange={e => setCost(e.target.value)} />
            </div>
            <div className="me-4">
              <div className="field-label">Location</div>
              <input type="text" placeholder="e.g., Rockville Auto Center" value={location} onChange={e => setLocation(e.target.value)} />
            </div>
            <div className="me-4">
              <div className="field-label">Receipt Upload</div>
              <label className="custom-file-upload">
                <Upload width={20} color={"#fff"} className="me-2" /> Upload
                <input type="file" onChange={(e) => setReceiptFile(e.target.files[0])} />
              </label>
              <div className="file-name">{receiptFile?.name}</div>
            </div>
            <div className="me-4">
              <div className="field-label">Next Replacement Reminder</div>
              <input type="text" placeholder="e.g., 78,000" value={nextReminder} onChange={e => setNextReminder(e.target.value)} />
            </div>
          </div>

          <div className="list row mb-5 mt-3">
            <div className="col-md-12 col-sm-12 col-xs-12">
              <button className="btn btn-default btn-sm float-right" onClick={goBack}> Cancel </button>
              <button className="btn btn-primary btn-sm float-right" onClick={handleSave}> Save </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default AddRepairRecord;
