import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { AuthService, VehicleService } from "../../services";
import { Upload } from "react-bootstrap-icons";
import { Breadcrumb } from "react-bootstrap";
import DatePicker from "react-datepicker";

const AddVehicleInspection = () => {
  const navigate = useNavigate();
  const params = useParams();
  const inspectionType = params.type; // 'yearly' or 'monthly'
  const isYearly = inspectionType === 'yearly';
  const title = isYearly ? 'Yearly Inspection' : 'Monthly Inspection';

  const [currentVehicle, setCurrentVehicle] = useState(null);
  const [inspectionDate, setInspectionDate] = useState(null);
  const [selectedFile, setSelectedFile] = useState(null);
  const [existingFiles, setExistingFiles] = 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) {
      fetchFiles();
    }
  }, [currentVehicle]);

  const fetchFiles = () => {
    const fileType = isYearly ? 'yearlyInspection' : 'monthlyInspection';
    VehicleService.getAllVechileFiles(currentVehicle.id, currentVehicle.vehicle_number, fileType)
      .then(res => setExistingFiles(res.data?.data?.files || []))
      .catch(() => setExistingFiles([]));
  };

  const getFileDownloadUrl = (fileUrl) => {
    const baseUrl = require('../../http-common').default?.defaults?.baseURL || '';
    return baseUrl.replace('/api', '') + fileUrl;
  };

  const handleSave = () => {
    if (!inspectionDate) {
      window.alert('Please select a date.');
      return;
    }

    // File upload is optional on add page.
    if (selectedFile) {
      const formData = new FormData();
      formData.append('file', selectedFile);
      const fileType = isYearly ? 'yearlyInspection' : 'monthlyInspection';
      VehicleService.uploadVechileFile(formData, currentVehicle.id, currentVehicle.vehicle_number, fileType, inspectionDate).then(() => {
        setSelectedFile(null);
        setInspectionDate(null);
        fetchFiles();
      });
      return;
    }

    goBack();
  };

  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 {title}</Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>Add {title} <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">{title}</h6>

          {existingFiles.length > 0 && (
            <>
              <div className="field-label mb-2">Existing Records</div>
              <table className="table table-sm table-bordered mb-4">
                <thead>
                  <tr>
                    <th>File Name</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  {existingFiles.map((file, idx) => (
                    <tr key={idx}>
                      <td>{file.name}</td>
                      <td>
                        <a href={getFileDownloadUrl(file.url)} target="_blank" rel="noopener noreferrer" className="btn btn-link btn-sm p-0">Download</a>
                      </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">Inspection Date</div>
              <DatePicker
                selected={inspectionDate}
                onChange={(date) => setInspectionDate(date)}
                dateFormat="MM/dd/yyyy"
                placeholderText="e.g., 03/01/2024"
                className="form-control"
              />
            </div>
            <div className="me-4">
              <div className="field-label">Inspection File (Optional)</div>
              <label className="custom-file-upload">
                <Upload width={20} color={"#fff"} className="me-2" /> Upload
                <input type="file" onChange={(e) => setSelectedFile(e.target.files[0])} />
              </label>
              <div className="file-name">{selectedFile?.name}</div>
            </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 AddVehicleInspection;
