import React, {useState, useEffect} from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { AuthService, VehicleRepairService, VehicleService } from "../../services";
import { vehicleSlice, selectVehicleError } from "./../../store";
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab } from "react-bootstrap";
import { Download, PencilSquare, Archive, Trash } from "react-bootstrap-icons";
import moment from "moment";
import { Export } from "../../shared/components";
import {
  FUEL_TYPE_TEXT,
  VEHICLE_TITLE_TEXT,
  REPAIR_PART_NAME_TEXT
} from "../../shared";

const ViewVehicle = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const urlParams = useParams();
  const [searchParams] = useSearchParams();
  const [monthlyDocs, setMonthlyDocs] = useState([]);
  const [yearlyDocs, setYearlyDocs] = useState([]);
  const [repairs, setRepairs] = useState([]);
  const [keyword, setKeyword] = useState('');
  const [sortingMonthly, setSortingMonthly] = useState({key: '', order: ''});
  const [sortingYearly, setSortingYearly] = useState({key: '', order: ''});
  const [sortingRepair, setSortingRepair] = useState({key: '', order: ''});
  const [selectedItemsMonthly, setSelectedItemsMonthly] = useState([]);
  const [selectedItemsYearly, setSelectedItemsYearly] = useState([]);
  const [selectedItemsRepair, setSelectedItemsRepair] = useState([]);
  const [filteredMonthlyDocs, setFilteredMonthlyDocs] = useState(monthlyDocs);
  const [filteredYearlyDocs, setFilteredYearlyDocs] = useState(yearlyDocs);
  const [filteredRepairs, setFilteredRepairs] = useState(repairs);
  const { updateVehicle, deleteVehicle, fetchAllVehicles } = vehicleSlice.actions;
  const [currentTab, setCurrentTab] = useState(searchParams.get('tab') || 'basicInfo');
  const [currentVehicle, setCurrentVehicle] = useState(undefined);
	
  const redirectTo = () => {
    navigate(`/vehicles/list`);
  }

  const goToEdit = (id) => {
    navigate(`/vehicles/edit/${id}?redirect=list&tab=${currentTab}`);
  }

  const download = () => {
    const downloadArr = [...selectedItemsMonthly, ...selectedItemsYearly];
    downloadArr.forEach((url) => {
      const a = document.createElement('a');
      a.href = url;
      a.download = '';
      document.body.append(a);
      a.click();
      document.body.removeChild(a);
    });
  }

  const refreshVehicleDocuments = async () => {
    if (!currentVehicle?.id || !currentVehicle?.vehicle_number) return;
    const getInspectionDate = (name) => {
      const arr1 = name.split('.');
      const prefix = arr1[0];
      if (prefix) {
        const arr2 = prefix.split('_');
        const dateNumber = arr2[arr2.length - 1];
        return dateNumber ? new Date(parseInt(dateNumber)).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : moment().format('MM/DD/YYYY');
      } else {
        return moment().format('MM/DD/YYYY');
      }
    };
    const monthlyInspectionDocs = (await VehicleService.getAllVechileFiles(currentVehicle.id, currentVehicle.vehicle_number, 'monthlyInspection'))?.data?.data?.files || [];
    const yearlyInspectionDocs = (await VehicleService.getAllVechileFiles(currentVehicle.id, currentVehicle.vehicle_number, 'yearlyInspection'))?.data?.data?.files || [];
    setMonthlyDocs(monthlyInspectionDocs?.map(item => ({ ...item, inspectionDate: getInspectionDate(item?.name) })));
    setYearlyDocs(yearlyInspectionDocs?.map(item => ({ ...item, inspectionDate: getInspectionDate(item?.name) })));
  };

  const deleteInspectionFile = async (fileType, fileName) => {
    if (!currentVehicle?.id || !fileName) return;
    if (!window.confirm('Are you sure you want to delete this inspection file?')) return;
    try {
      await VehicleService.deleteVechileFile(currentVehicle.id, fileType, fileName);
      await refreshVehicleDocuments();
    } catch (error) {
      console.error('Failed to delete inspection file:', error);
      window.alert('Failed to delete inspection file.');
    }
  };

  const deactivateVehicle = () => {
    const data = {
      status: 'inactive'
    };
    dispatch(deleteVehicle({id: urlParams.id, data}));
    redirectTo();
  }

  useEffect(() => {
    const getInspectionDate = (name) => {
      const arr1 = name.split('.');
      const prefix = arr1[0];
      if (prefix) {
        const arr2 = prefix.split('_');
        const dateNumber = arr2[arr2.length - 1];
        return dateNumber ? new Date(parseInt(dateNumber)).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : moment().format('MM/DD/YYYY');
      } else {
        return moment().format('MM/DD/YYYY');
      }
    }
    const getAllDocuments = async (vid, name) => {
      const monthlyInspectionDocs = (await VehicleService.getAllVechileFiles(vid, name, 'monthlyInspection'))?.data?.data?.files || [];
      const yearlyInspectionDocs = (await VehicleService.getAllVechileFiles(vid, name, 'yearlyInspection'))?.data?.data?.files || [];
      setMonthlyDocs(monthlyInspectionDocs?.map(item => ({ ...item, inspectionDate: getInspectionDate(item?.name) })));
      setYearlyDocs(yearlyInspectionDocs?.map(item => ({ ...item, inspectionDate: getInspectionDate(item?.name) })));
    };
    const getAllRepairs = async (vid) => {
      const v_repairs = (await VehicleRepairService.getAll(vid)).data;
      setRepairs(v_repairs);
    }
    if (!AuthService.canViewVechiles()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change an admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
    if (!currentVehicle) {
      VehicleService.getVehicle(urlParams.id).then((data) => {
        setCurrentVehicle(data.data);
        getAllDocuments(data.data?.id, data.data?.vehicle_number);
        getAllRepairs(data.data?.id);
      });
    } else {
      getAllDocuments(currentVehicle?.id, currentVehicle?.vehicle_number);
      getAllRepairs(currentVehicle?.id);
    }
  }, []);

  useEffect(() => {
    setFilteredMonthlyDocs(monthlyDocs?.filter(item => item?.name?.toLowerCase().includes(keyword.toLowerCase()) || item?.inspectionDate?.includes(keyword.toLowerCase())));
    setFilteredYearlyDocs(yearlyDocs?.filter(item => item?.name?.toLowerCase().includes(keyword.toLowerCase()) || item?.inspectionDate?.includes(keyword.toLowerCase())));
  }, [keyword, yearlyDocs, monthlyDocs]);

  useEffect(() => {
    setFilteredRepairs(repairs?.filter(item => 
      item?.repair_description?.toLowerCase().includes(keyword.toLowerCase()) || 
      item?.repair_date?.includes(keyword.toLowerCase()) || 
      item?.repair_location?.toLowerCase().includes(keyword.toLowerCase()) || 
      item?.repair_price?.toLowerCase().includes(keyword.toLowerCase()) ||
      item?.part_name?.toLowerCase().includes(keyword.toLowerCase())
    ));
  }, [keyword, repairs]);

  useEffect(() => {
    const newYearlyDocs = [...yearlyDocs];
    const sortedYearlyDocs = sortingYearly.key === '' ? newYearlyDocs : newYearlyDocs.sort((a, b) => {
      return a[sortingYearly.key]?.localeCompare(b[sortingYearly.key]);
    });
    setYearlyDocs(
      sortingMonthly.order === 'asc' ? sortedYearlyDocs : sortedYearlyDocs.reverse()
    );
  }, [sortingYearly]);

  useEffect(() => {
    const newMonthlyDocs = [...monthlyDocs];
    const sortedMonthlyDocs = sortingMonthly.key === '' ? newMonthlyDocs : newMonthlyDocs.sort((a, b) => {
      return a[sortingMonthly.key]?.localeCompare(b[sortingMonthly.key]);
    });
    setMonthlyDocs(
      sortingMonthly.order === 'asc' ? sortedMonthlyDocs : sortedMonthlyDocs.reverse()
    );
  }, [sortingMonthly]);

  useEffect(() => {
    const newRepairs = [...repairs];
    const sortedRepairs = sortingRepair.key === '' ? newRepairs : newRepairs.sort((a, b) => {
      return a[sortingRepair.key]?.localeCompare(b[sortingRepair.key]);
    });
    setRepairs(
      sortingRepair.order === 'asc' ? sortedRepairs : sortedRepairs.reverse()
    );
  }, [sortingRepair]);

  // Helper to format Yes/No values
  const formatYesNo = (value) => {
    if (value === true) return 'Yes';
    if (value === false) return 'No';
    return value || '';
  };

  const columnsMonthly = [
    { key: 'name', label: 'Monthly Vehicle Inspection Sheet' },
    { key: 'inspectionDate', label: 'Vehicle Inspection Date' },
    { key: 'createdAt', label: 'Date Added' }
  ];

  const columnsYearly = [
    { key: 'name', label: 'Yearly Vehicle Inspection Sheet' },
    { key: 'inspectionDate', label: 'Vehicle Inspection Date' },
    { key: 'createdAt', label: 'Date Added' }
  ];

  const columnsRepair = [
    { key: 'part_name', label: 'Part Name', show: true },
    { key: 'repair_date', label: 'Replacement Date', show: true },
    { key: 'mileage_at_replacement', label: 'Mileage', show: true },
    { key: 'quantity', label: 'Quantity', show: true },
    { key: 'repair_price', label: 'Cost', show: true },
    { key: 'repair_location', label: 'Location', show: true },
    { key: 'next_replacement_reminder', label: 'Next Reminder', show: true },
    { key: 'create_date', label: 'Date Added', show: true }
  ];

  const sortTableWithFieldMonthly = (key) => {
    let newSorting = { key, order: 'asc' };
    if (sortingMonthly.key === key && sortingMonthly.order === 'asc') {
      newSorting = {...newSorting, order: 'desc'};
    }
    setSortingMonthly(newSorting);
  }

  const sortTableWithFieldYearly = (key) => {
    let newSorting = { key, order: 'asc' };
    if (sortingYearly.key === key && sortingYearly.order === 'asc') {
      newSorting = {...newSorting, order: 'desc'};
    }
    setSortingYearly(newSorting);
  }

  const sortTableWithFieldRepair = (key) => {
    let newSorting = { key, order: 'asc' };
    if (sortingRepair.key === key && sortingRepair.order === 'asc') {
      newSorting = {...newSorting, order: 'desc'};
    }
    setSortingRepair(newSorting);
  }

  const toggleSelectedAllItemsMonthly = () => {
    if (selectedItemsMonthly.length !== filteredMonthlyDocs.length || selectedItemsMonthly.length === 0) {
      const newSelectedItems = [...filteredMonthlyDocs].map((doc) => doc.url);
      setSelectedItemsMonthly(newSelectedItems);
    } else {
      setSelectedItemsMonthly([]);
    }
  }

  const toggleSelectedAllItemsYearly = () => {
    if (selectedItemsYearly.length !== filteredYearlyDocs.length || selectedItemsYearly.length === 0) {
      const newSelectedItems = [...filteredYearlyDocs].map((doc) => doc.url);
      setSelectedItemsYearly(newSelectedItems);
    } else {
      setSelectedItemsYearly([]);
    }
  }

  const toggleSelectedAllItemsRepair = () => {
    if (selectedItemsRepair.length !== filteredRepairs.length || filteredRepairs.length === 0) {
      const newSelectedItems = [...filteredRepairs].map((doc) => doc.id);
      setSelectedItemsRepair(newSelectedItems);
    } else {
      setSelectedItemsRepair([]);
    }
  }

  const toggleItemYearly = (id) => {
    if (selectedItemsYearly.includes(id)) {
      const newSelectedItems = [...selectedItemsYearly].filter((item) => item !== id);
      setSelectedItemsYearly(newSelectedItems);
    } else {
      const newSelectedItems = [...selectedItemsYearly, id];
      setSelectedItemsYearly(newSelectedItems);
    }
  }

  const toggleItemMonthly = (id) => {
    if (selectedItemsMonthly.includes(id)) {
      const newSelectedItems = [...selectedItemsMonthly].filter((item) => item !== id);
      setSelectedItemsMonthly(newSelectedItems);
    } else {
      const newSelectedItems = [...selectedItemsMonthly, id];
      setSelectedItemsMonthly(newSelectedItems);
    }
  }

  const toggleItemRepair = (id) => {
    if (selectedItemsRepair.includes(id)) {
      const newSelectedItems = [...selectedItemsRepair].filter((item) => item !== id);
      setSelectedItemsRepair(newSelectedItems);
    } else {
      const newSelectedItems = [...selectedItemsRepair, id];
      setSelectedItemsRepair(newSelectedItems);
    }
  }

  const getSortingImgMonthly = (key) => {
    return sortingMonthly.key === key ? (sortingMonthly.order === 'asc' ? 'up_arrow' : 'down_arrow') : 'default';
  }

  const getSortingImgYearly = (key) => {
    return sortingYearly.key === key ? (sortingYearly.order === 'asc' ? 'up_arrow' : 'down_arrow') : 'default';
  }

  const getSortingImgRepair = (key) => {
    return sortingRepair.key === key ? (sortingRepair.order === 'asc' ? 'up_arrow' : 'down_arrow') : 'default';
  }

  const checkSelectAllMonthly = () => {
    return selectedItemsMonthly.length === filteredMonthlyDocs.length && selectedItemsMonthly.length > 0;
  }

  const checkSelectAllYearly = () => {
    return selectedItemsYearly.length === filteredYearlyDocs.length && selectedItemsYearly.length > 0;
  }

  const checkSelectAllRepair = () => {
    return selectedItemsRepair.length === filteredRepairs.length && selectedItemsRepair.length > 0;
  }

  const changeTab = (k) => {
    setCurrentTab(k);
    setKeyword('');
    setSortingMonthly({key: '', order: ''});
    setSortingYearly({key: '', order: ''});
    setSortingRepair({key: '', order: ''});
  }

  const tableMonthly = (
    <div className="list row mb-4">
      <div className="col-md-12">
        <table className="personnel-info-table"> 
          <thead>
            <tr>
              <th className="th-index">No.</th>
              {columnsMonthly.map((column, index) => (
                <th className="sortable-header" key={index}>
                  {column.label} <span className="float-right" onClick={() => sortTableWithFieldMonthly(column.key)}><img src={`/images/${getSortingImgMonthly(column.key)}.png`}></img></span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filteredMonthlyDocs.map((doc, index) => (
              <tr key={doc.url}>
                <td className="td-index">{index + 1}</td>
                <td>
                  <PencilSquare size={14} className="clickable me-2" onClick={() => navigate(`/vehicles/${currentVehicle?.id}/inspections/monthly/edit?fileName=${encodeURIComponent(doc?.name)}&date=${encodeURIComponent(doc?.inspectionDate || '')}`)} />
                  <Trash size={14} className="clickable me-2 text-danger" onClick={() => deleteInspectionFile('monthlyInspection', doc?.name)} />
                  <a className="btn btn-link btn-sm" href={doc?.url} target="_blank">{doc?.name}</a>
                </td>
                <td>{doc?.inspectionDate}</td>
                <td>{new Date(doc?.createdAt).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'})}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );

  const tableYearly = (
    <div className="list row mb-4">
      <div className="col-md-12">
        <table className="personnel-info-table"> 
          <thead>
            <tr>
              <th className="th-index">No.</th>
              {columnsYearly.map((column, index) => (
                <th className="sortable-header" key={index}>
                  {column.label} <span className="float-right" onClick={() => sortTableWithFieldYearly(column.key)}><img src={`/images/${getSortingImgYearly(column.key)}.png`}></img></span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filteredYearlyDocs.map((doc, index) => (
              <tr key={doc.url}>
                <td className="td-index">{index + 1}</td>
                <td>
                  <PencilSquare size={14} className="clickable me-2" onClick={() => navigate(`/vehicles/${currentVehicle?.id}/inspections/yearly/edit?fileName=${encodeURIComponent(doc?.name)}&date=${encodeURIComponent(doc?.inspectionDate || '')}`)} />
                  <Trash size={14} className="clickable me-2 text-danger" onClick={() => deleteInspectionFile('yearlyInspection', doc?.name)} />
                  <a className="btn btn-link btn-sm" href={doc?.url} target="_blank">{doc?.name}</a>
                </td>
                <td>{doc?.inspectionDate}</td>
                <td>{new Date(doc?.createdAt).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'})}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );

  const tableRepair = (
    <div className="list row mb-4">
      <div className="col-md-12">
        <table className="personnel-info-table"> 
          <thead>
            <tr>
              <th className="th-index">No.</th>
              {columnsRepair.map((column, index) => (
                <th className="sortable-header" key={index}>
                  {column.label} <span className="float-right" onClick={() => sortTableWithFieldRepair(column.key)}><img src={`/images/${getSortingImgRepair(column.key)}.png`}></img></span>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filteredRepairs?.map((repair, index) => (
              <tr key={repair.id}>
                <td className="td-index">{index + 1}</td>
                <td>
                  <PencilSquare size={14} className="clickable me-2" onClick={() => navigate(`/vehicles/${currentVehicle?.id}/repairs/edit/${repair?.id}`)} />
                  {repair?.part_name === 'other'
                    ? (repair?.part_name_other || REPAIR_PART_NAME_TEXT[repair?.part_name] || repair?.repair_description)
                    : (REPAIR_PART_NAME_TEXT[repair?.part_name] || repair?.part_name || repair?.repair_description)}
                </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>{repair?.create_date ? new Date(repair?.create_date).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : repair?.repair_date}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );

  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 active>
            View Vehicle Information
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <div className="col-md-12 text-primary">
        <h4>View Vehicle Information <button className="btn btn-link btn-sm" onClick={() => {redirectTo()}}>Back</button></h4> 
      </div>
      <div className="app-main-content-list-container form-page">
        <div className="app-main-content-list-func-container">
          <Tabs activeKey={currentTab} id="vehicles-tab" onSelect={k => changeTab(k)}>
            <Tab eventKey="basicInfo" title="Basic Information">
              <h6 className="text-primary">Basic Information</h6>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Vehicle Number</div> 
                  <div className="field-value">{currentVehicle?.vehicle_number}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Responsible Driver</div> 
                  <div className="field-value">{currentVehicle?.responsible_driver}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Seating Capacity</div> 
                  <div className="field-value">{currentVehicle?.capacity}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Mileage</div> 
                  <div className="field-value">{currentVehicle?.mileage}</div>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Make</div> 
                  <div className="field-value">{currentVehicle?.make}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Model</div> 
                  <div className="field-value">{currentVehicle?.vehicle_model}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Year</div> 
                  <div className="field-value">{currentVehicle?.year}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">VIN Number</div> 
                  <div className="field-value">{currentVehicle?.vin}</div>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">License Plate</div> 
                  <div className="field-value">{currentVehicle?.tag}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">GPS ID</div> 
                  <div className="field-value">{currentVehicle?.gps_tag}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">E-ZPass</div> 
                  <div className="field-value">{currentVehicle?.ezpass}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Lift Equipped</div> 
                  <div className="field-value">{formatYesNo(currentVehicle?.has_lift_equip)}</div>
                </div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Fuel Type</div> 
                  <div className="field-value">{FUEL_TYPE_TEXT[currentVehicle?.fuel_type] || currentVehicle?.fuel_type}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Title</div> 
                  <div className="field-value">
                    {VEHICLE_TITLE_TEXT[currentVehicle?.title] || currentVehicle?.title}
                    {currentVehicle?.title === 'other' && currentVehicle?.title_other && ` (${currentVehicle?.title_other})`}
                  </div>
                </div>
              </div>

              <h6 className="text-primary">Check List</h6>
              <div className="app-main-content-fields-section column">
                <ul>
                  {currentVehicle?.checklist?.map((item, index) => <li key={index}>{item}</li>)}
                </ul>
              </div>

              <h6 className="text-primary">Additional Information</h6>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Notes and Attachments</div>
                  <div className="field-value">{currentVehicle?.note}</div>
                </div>
              </div>
            </Tab>

            <Tab eventKey="complianceDeadlines" title="Compliance & Deadlines">
              <h6 className="text-primary">Compliance & Deadlines</h6>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Insurance Expiration Date</div>
                  <div className="field-value">{currentVehicle?.insurance_start_date || currentVehicle?.insurance_expire_on}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Vehicle Registration Date</div>
                  <div className="field-value">{currentVehicle?.vehicle_registration_date || currentVehicle?.title_registration_on}</div>
                </div>
              </div>
            </Tab>

            <Tab eventKey="documents" title="Documents & Records">
              <div className="d-flex justify-content-between align-items-center mb-3">
                <h6 className="text-primary mb-0">Yearly Inspection</h6>
                <button className="btn btn-primary btn-sm" onClick={() => navigate(`/vehicles/${currentVehicle?.id}/inspections/yearly/add`)}>+ Add Yearly Inspection</button>
              </div>
              {tableYearly}
              <div className="d-flex justify-content-between align-items-center mb-3 mt-4">
                <h6 className="text-primary mb-0">Monthly Inspection</h6>
                <button className="btn btn-primary btn-sm" onClick={() => navigate(`/vehicles/${currentVehicle?.id}/inspections/monthly/add`)}>+ Add Monthly Inspection</button>
              </div>
              {tableMonthly}
              <div className="d-flex justify-content-between align-items-center mb-3 mt-4">
                <h6 className="text-primary mb-0">Repair & Maintenance Record</h6>
                <button className="btn btn-primary btn-sm" onClick={() => navigate(`/vehicles/${currentVehicle?.id}/repairs/add`)}>+ Add Repair Record</button>
              </div>
              {tableRepair}
            </Tab>
          </Tabs>
          <div className="list-func-panel">
            {currentTab === 'documents' && (
              <>
                <input className="me-2 with-search-icon" type="text" placeholder="Search" value={keyword} onChange={(e) => setKeyword(e.currentTarget.value)} />
                <Export 
                  columns={columnsRepair} 
                  data={filteredRepairs} 
                  filename={`vehicle-${currentVehicle?.vehicle_number}-repairs`} 
                />
              </>
            )}
            {currentTab !== 'documents' && (
              <button className="btn btn-primary ms-2" onClick={() => goToEdit(currentVehicle?.id)}><PencilSquare className="me-2" size={16}></PencilSquare>Edit</button>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default ViewVehicle;
