import React, { useState, useEffect, useContext } from 'react';
import { Link, useMatch, useNavigate, useParams, useLocation } from 'react-router-dom';
import henceforthApi from '../utils/henceforthApi';
import { GlobalContext } from "../context/Provider";
import PaginationLayout from "../components/PaginationLayout";
import moment from 'moment';
import { toast } from 'react-toastify';
import Swal from 'sweetalert2';

interface modalData {
  name: string;
}
interface modalFecth {
  brand_id: null | string;
  brand_name: string;
  created_at: string;
  name: string;
  _id: string;
}
interface dateFetch {
  total_count: number;
  data: Array<modalFecth>;
}
interface modalG {
  created_at: string;
  modal: dateFetch;
  name: string;
  _id: string;
}
interface modalObje {
  total_count: number;
  data: Array<modalData>;
}
interface Arrays {
  name: string;
  _id: string;
  modal: modalObje;
}
interface state {
  brand: Array<Arrays>;
  total_count: null | number;
  loading: boolean;
}

const Vehicle = () => {
  const [activeTab, setActiveTab] = useState<'brands' | 'types' | 'colors'>('brands');
  const [dropdownOpen, setDropdownOpen] = useState(false);

  let match: any = useMatch("/vehicles/:page");
  let navigate = useNavigate();
  let location = useLocation();
  const { authState, handleFilter, handlePagination, handleError } = useContext(GlobalContext);
  const params: any = useParams();
  const newParam = new URLSearchParams(location.search);
  const [searchData, setSearchData] = useState<string>("");
  const [loading, setLoading] = useState(true);
  const [storedata, setStoredata] = useState([]);
  const [state, setState] = useState({
    brand: [],
    total_count: null,
    loading: false
  } as state);

  // --- Vehicle Types State ---
  const [typesList, setTypesList] = useState<Array<any>>([]);
  const [typesLoading, setTypesLoading] = useState(false);
  const [typesTotalCount, setTypesTotalCount] = useState(0);
  const [typesPage, setTypesPage] = useState(1);
  const [typeModalOpen, setTypeModalOpen] = useState(false);
  const [editingType, setEditingType] = useState<any>(null);
  const [typeNameInput, setTypeNameInput] = useState('');
  const [savingType, setSavingType] = useState(false);

  // --- Vehicle Colors State ---
  const [colorsList, setColorsList] = useState<Array<any>>([]);
  const [colorsLoading, setColorsLoading] = useState(false);
  const [colorsTotalCount, setColorsTotalCount] = useState(0);
  const [colorsPage, setColorsPage] = useState(1);
  const [colorModalOpen, setColorModalOpen] = useState(false);
  const [editingColor, setEditingColor] = useState<any>(null);
  const [colorNameInput, setColorNameInput] = useState('');
  const [savingColor, setSavingColor] = useState(false);

  if (authState.access_token) { henceforthApi.setToken(authState.access_token); }
  const limit = 10;

  // --- Get Brands ---
  const GetVehicle = async () => {
    let search = newParam.has("search") ? newParam.get("search") : "";
    try {
      setLoading(true);
      let apiRes = await henceforthApi.Vehicle.getBrand(String(search), Number(params.page) - 1, limit);
      let brandData = apiRes.data;
      let allBrandData = brandData.data;
      let total_count = brandData.total_count;
      if (Array.isArray(allBrandData)) {
        let newBrand = [] as Array<modalG>;
        await Promise.all(allBrandData.map(async (res) => {
          try {
            const modalsData = await henceforthApi.Vehicle.getModals(res.name, 0, '');
            newBrand.push({
              ...res,
              modal: modalsData.data,
            });
          } catch (error: any) { }
        }));

        setState({
          ...state,
          brand: newBrand,
          total_count,
          loading: false
        });
      }
    } catch (error: any) {
      handleError(error);
    } finally {
      setLoading(false);
    }
  };

  // --- Get Vehicle Types ---
  const getVehicleTypes = async (pageNumber: number = 1) => {
    try {
      setTypesLoading(true);
      const res = await henceforthApi.Vehicle.getTypes(pageNumber - 1, limit);
      const data = res?.data?.data || [];
      const total = res?.data?.total_count || 0;
      setTypesList(data);
      setTypesTotalCount(total);
      setTypesPage(pageNumber);
    } catch (err: any) {
      setTypesList([]);
      setTypesTotalCount(0);
      handleError(err);
    } finally {
      setTypesLoading(false);
    }
  };

  // --- Save / Edit Vehicle Type ---
  const handleSaveType = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = typeNameInput.trim();
    if (!trimmed) {
      toast.warn("Please enter vehicle type name");
      return;
    }
    setSavingType(true);
    try {
      const payload: any = { name: trimmed };
      if (editingType?._id) {
        payload._id = editingType._id;
      }
      await henceforthApi.Vehicle.addType(payload);
      Swal.fire({
        title: editingType?._id ? "Type Updated" : "Type Added",
        text: editingType?._id ? "Vehicle type updated successfully" : "Vehicle type added successfully",
        icon: "success",
        confirmButtonText: "OK",
      });
      setTypeModalOpen(false);
      setEditingType(null);
      setTypeNameInput('');
      getVehicleTypes(typesPage);
    } catch (err: any) {
      const errorMsg = err?.response?.body?.error_description || err?.response?.body?.message || (typeof err === 'string' ? err : "Failed to save vehicle type");
      Swal.fire({
        title: "Failed",
        text: errorMsg,
        icon: "error",
        confirmButtonText: "Cancel",
      });
    } finally {
      setSavingType(false);
    }
  };

  // --- Delete Vehicle Type ---
  const handleDeleteType = (id: string) => {
    Swal.fire({
      title: "Are you sure?",
      text: "You won't be able to revert this!",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, delete it!",
    }).then(async (result: any) => {
      if (result.isConfirmed) {
        try {
          await henceforthApi.Vehicle.delType(id);
          Swal.fire({
            title: "Deleted",
            text: "Vehicle type deleted successfully",
            icon: "success",
            confirmButtonText: "OK",
          });
          getVehicleTypes(typesPage);
        } catch (err: any) {
          Swal.fire({
            title: "Delete Failed",
            text: err?.response?.body?.error_description || "Failed to delete",
            icon: "error",
            confirmButtonText: "Cancel",
          });
        }
      }
    });
  };

  // --- Get Vehicle Colors ---
  const getVehicleColors = async (pageNumber: number = 1) => {
    try {
      setColorsLoading(true);
      const res = await henceforthApi.Vehicle.getColors(pageNumber - 1, limit);
      const data = res?.data?.data || [];
      const total = res?.data?.total_count || 0;
      setColorsList(data);
      setColorsTotalCount(total);
      setColorsPage(pageNumber);
    } catch (err: any) {
      setColorsList([]);
      setColorsTotalCount(0);
      handleError(err);
    } finally {
      setColorsLoading(false);
    }
  };

  // --- Save / Edit Vehicle Color ---
  const handleSaveColor = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = colorNameInput.trim();
    if (!trimmed) {
      toast.warn("Please enter vehicle color name");
      return;
    }
    setSavingColor(true);
    try {
      const payload: any = { name: trimmed };
      if (editingColor?._id) {
        payload._id = editingColor._id;
      }
      await henceforthApi.Vehicle.addColor(payload);
      Swal.fire({
        title: editingColor?._id ? "Color Updated" : "Color Added",
        text: editingColor?._id ? "Vehicle color updated successfully" : "Vehicle color added successfully",
        icon: "success",
        confirmButtonText: "OK",
      });
      setColorModalOpen(false);
      setEditingColor(null);
      setColorNameInput('');
      getVehicleColors(colorsPage);
    } catch (err: any) {
      const errorMsg = err?.response?.body?.error_description || err?.response?.body?.message || (typeof err === 'string' ? err : "Failed to save vehicle color");
      Swal.fire({
        title: "Failed",
        text: errorMsg,
        icon: "error",
        confirmButtonText: "Cancel",
      });
    } finally {
      setSavingColor(false);
    }
  };

  // --- Delete Vehicle Color ---
  const handleDeleteColor = (id: string) => {
    Swal.fire({
      title: "Are you sure?",
      text: "You won't be able to revert this!",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, delete it!",
    }).then(async (result: any) => {
      if (result.isConfirmed) {
        try {
          await henceforthApi.Vehicle.delColor(id);
          Swal.fire({
            title: "Deleted",
            text: "Vehicle color deleted successfully",
            icon: "success",
            confirmButtonText: "OK",
          });
          getVehicleColors(colorsPage);
        } catch (err: any) {
          Swal.fire({
            title: "Delete Failed",
            text: err?.response?.body?.error_description || "Failed to delete",
            icon: "error",
            confirmButtonText: "Cancel",
          });
        }
      }
    });
  };

  const categoryName = activeTab === 'brands' ? 'Brands & Models' : activeTab === 'types' ? 'Vehicle Types' : 'Vehicle Colors';

  useEffect(() => {
    let search = newParam.has("search") ? newParam.get("search") : "";
    setSearchData(search || "");
    if (activeTab === 'brands') {
      GetVehicle();
    }
    setStoredata([...storedata]);
  }, [params.page, newParam.get("search")]);

  return (
    <>
      <div className="ibox animated fadeInRight">
        <div className="ibox-title d-flex align-items-center justify-content-between">
          <h5>
            {activeTab === 'brands' && "List of all Vehicles"}
            {activeTab === 'types' && "List of all Vehicle Types"}
            {activeTab === 'colors' && "List of all Vehicle Colors"}
          </h5>
          <div className="d-flex align-items-center justify-content-end">
            {/* Category Dropdown (identical to Coupons, Users, Rides pages) */}
            <div className={`dropdown theme me-3 ${dropdownOpen ? 'show' : ''}`}>
              <button
                className="btn dashboard-button pe-4 ps-4 dropdown-toggle shadow-none text-white"
                id="sortDropdown"
                type="button"
                data-bs-toggle="dropdown"
                aria-expanded={dropdownOpen}
                onClick={() => setDropdownOpen(!dropdownOpen)}
              >
                {categoryName}
                <i className="fas fa-chevron-down bi-chevron-down ms-2 unset-icon" style={{ fontSize: "12px" }}></i>
              </button>
              <ul className={`dropdown-menu share-icons ${dropdownOpen ? 'show' : ''}`} aria-labelledby="sortDropdown">
                <li className="cursor-pointer">
                  <a
                    className="dropdown-item"
                    onClick={() => {
                      setActiveTab('brands');
                      setDropdownOpen(false);
                      setSearchData("");
                    }}
                  >
                    Brands &amp; Models
                  </a>
                </li>
                <li className="cursor-pointer">
                  <a
                    className="dropdown-item"
                    onClick={() => {
                      setActiveTab('types');
                      setDropdownOpen(false);
                      setSearchData("");
                      getVehicleTypes(1);
                    }}
                  >
                    Vehicle Types
                  </a>
                </li>
                <li className="cursor-pointer">
                  <a
                    className="dropdown-item"
                    onClick={() => {
                      setActiveTab('colors');
                      setDropdownOpen(false);
                      setSearchData("");
                      getVehicleColors(1);
                    }}
                  >
                    Vehicle Colors
                  </a>
                </li>
              </ul>
            </div>

            {/* Action Button */}
            {activeTab === 'brands' && (
              <Link to="/vehicle/add" className="link-style">
                <button className="btn btn-color" type="button">Add Vehicle</button>
              </Link>
            )}
            {activeTab === 'types' && (
              <button
                className="btn btn-color"
                type="button"
                onClick={() => {
                  setEditingType(null);
                  setTypeNameInput('');
                  setTypeModalOpen(true);
                }}
              >
                Add Type
              </button>
            )}
            {activeTab === 'colors' && (
              <button
                className="btn btn-color"
                type="button"
                onClick={() => {
                  setEditingColor(null);
                  setColorNameInput('');
                  setColorModalOpen(true);
                }}
              >
                Add Color
              </button>
            )}
          </div>
        </div>

        <div className="ibox-content">
          {/* Search Bar */}
          <form onSubmit={(e: any) => e.preventDefault()}>
            <div className="input-group form-group">
              <input
                name="search"
                value={searchData}
                onChange={(e: any) => {
                  setSearchData(e.target.value);
                  if (activeTab === 'brands') {
                    handleFilter(e.target.name, e.target.value);
                  }
                }}
                placeholder={
                  activeTab === 'brands'
                    ? "Search by Vehicle brand "
                    : activeTab === 'types'
                    ? "Search by Vehicle type "
                    : "Search by Vehicle color "
                }
                type="text"
                className="form-control form-control-sm"
              />
            </div>
          </form>

          {/* ================= VIEW 1: BRANDS & MODELS ================= */}
          {activeTab === 'brands' && (
            <div className="container-fluid mt-4 px-0">
              <div className="table-responsive">
                <table className="table table-striped">
                  <thead>
                    <tr>
                      <th>Sr No.</th>
                      <th>Vehicle Brand</th>
                      <th>Vehicle Model</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  {!loading && (
                    <tbody>
                      {Array.isArray(state.brand) && state.brand.length > 0 ? (
                        state.brand.map((res: any, index: number) => (
                          <tr key={res._id}>
                            <td>
                              {params.page === "0"
                                ? index + 1
                                : (Number(params.page) - 1) * limit + (index + 1)}.
                            </td>
                            <td>{res?.name ? res?.name : "Not avialable"}</td>
                            <td>
                              <div className="d-flex">
                                {res?.modal?.total_count != 0 ? (
                                  res?.modal?.data?.slice(0, 6).map((item: any, idx: number) => (
                                    <p key={idx} className="mb-0 me-1">
                                      {item?.name?.length
                                        ? item?.name +
                                          `${idx < res?.modal?.data?.length - 1 ? (idx < 5 ? ', ' : '') : ''}`
                                        : "Not available"}
                                    </p>
                                  ))
                                ) : (
                                  "Not available"
                                )}
                              </div>
                            </td>
                            <td>
                              <div className="d-flex">
                                <Link
                                  to={`/vehicle-details/1/${res?._id}`}
                                  className="btn btn-xs btn-white me-2"
                                >
                                  <i className="fas fa-eye me-1"></i>View
                                </Link>
                              </div>
                            </td>
                          </tr>
                        ))
                      ) : (
                        <tr>
                          <td colSpan={12} className="text-center">
                            Sorry! no data to display
                          </td>
                        </tr>
                      )}
                    </tbody>
                  )}
                </table>
              </div>
              <PaginationLayout
                count={Number(state.total_count)}
                data={state.brand}
                page={Number(params.page)}
                limit={Number(limit)}
                loading={loading}
                onPageChange={(val) => handlePagination(val)}
              />
            </div>
          )}

          {/* ================= VIEW 2: VEHICLE TYPES ================= */}
          {activeTab === 'types' && (
            <div className="container-fluid mt-4 px-0">
              <div className="table-responsive">
                <table className="table table-striped">
                  <thead>
                    <tr>
                      <th>Sr No.</th>
                      <th>Vehicle Type</th>
                      <th>Created Date</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  {!typesLoading && (
                    <tbody>
                      {typesList.length > 0 ? (
                        typesList
                          .filter((item) =>
                            searchData
                              ? item.name?.toLowerCase().includes(searchData.toLowerCase())
                              : true
                          )
                          .map((item, index) => (
                            <tr key={item._id}>
                              <td>{(typesPage - 1) * limit + (index + 1)}.</td>
                              <td>{item?.name ? item?.name : "Not available"}</td>
                              <td>
                                {item?.created_at
                                  ? moment(Number(item?.created_at)).format("MMM DD, YYYY")
                                  : "Not available"}
                              </td>
                              <td>
                                <div className="d-flex">
                                  <button
                                    className="btn btn-xs btn-white me-2"
                                    onClick={() => {
                                      setEditingType(item);
                                      setTypeNameInput(item.name);
                                      setTypeModalOpen(true);
                                    }}
                                  >
                                    <i className="fas fa-pencil-alt me-1"></i>Edit
                                  </button>
                                  <button
                                    className="btn btn-xs btn-white me-2"
                                    onClick={() => handleDeleteType(item._id)}
                                  >
                                    <i className="fas fa-trash-alt me-1"></i>Delete
                                  </button>
                                </div>
                              </td>
                            </tr>
                          ))
                      ) : (
                        <tr>
                          <td colSpan={12} className="text-center">
                            Sorry! no data to display
                          </td>
                        </tr>
                      )}
                    </tbody>
                  )}
                </table>
              </div>
              <PaginationLayout
                count={typesTotalCount}
                data={typesList}
                page={typesPage}
                limit={limit}
                loading={typesLoading}
                onPageChange={(page: number) => getVehicleTypes(page)}
              />
            </div>
          )}

          {/* ================= VIEW 3: VEHICLE COLORS ================= */}
          {activeTab === 'colors' && (
            <div className="container-fluid mt-4 px-0">
              <div className="table-responsive">
                <table className="table table-striped">
                  <thead>
                    <tr>
                      <th>Sr No.</th>
                      <th>Vehicle Color</th>
                      <th>Created Date</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  {!colorsLoading && (
                    <tbody>
                      {colorsList.length > 0 ? (
                        colorsList
                          .filter((item) =>
                            searchData
                              ? item.name?.toLowerCase().includes(searchData.toLowerCase())
                              : true
                          )
                          .map((item, index) => (
                            <tr key={item._id}>
                              <td>{(colorsPage - 1) * limit + (index + 1)}.</td>
                              <td>
                                <span
                                  className="me-2"
                                  style={{
                                    display: "inline-block",
                                    width: "14px",
                                    height: "14px",
                                    borderRadius: "50%",
                                    backgroundColor: item?.name?.toLowerCase().trim(),
                                    border: "1px solid #ccc",
                                    verticalAlign: "middle"
                                  }}
                                ></span>
                                <span>{item?.name ? item?.name : "Not available"}</span>
                              </td>
                              <td>
                                {item?.created_at
                                  ? moment(Number(item?.created_at)).format("MMM DD, YYYY")
                                  : "Not available"}
                              </td>
                              <td>
                                <div className="d-flex">
                                  <button
                                    className="btn btn-xs btn-white me-2"
                                    onClick={() => {
                                      setEditingColor(item);
                                      setColorNameInput(item.name);
                                      setColorModalOpen(true);
                                    }}
                                  >
                                    <i className="fas fa-pencil-alt me-1"></i>Edit
                                  </button>
                                  <button
                                    className="btn btn-xs btn-white me-2"
                                    onClick={() => handleDeleteColor(item._id)}
                                  >
                                    <i className="fas fa-trash-alt me-1"></i>Delete
                                  </button>
                                </div>
                              </td>
                            </tr>
                          ))
                      ) : (
                        <tr>
                          <td colSpan={12} className="text-center">
                            Sorry! no data to display
                          </td>
                        </tr>
                      )}
                    </tbody>
                  )}
                </table>
              </div>
              <PaginationLayout
                count={colorsTotalCount}
                data={colorsList}
                page={colorsPage}
                limit={limit}
                loading={colorsLoading}
                onPageChange={(page: number) => getVehicleColors(page)}
              />
            </div>
          )}
        </div>
      </div>

      {/* --- Modal: Add / Edit Vehicle Type --- */}
      <div
        className={`modal fade common-modal report-modal ${typeModalOpen ? 'show' : ''}`}
        data-bs-backdrop="static"
        tabIndex={-1}
        role={typeModalOpen ? 'dialog' : ''}
        style={{
          display: typeModalOpen ? 'block' : 'none',
          backgroundColor: 'rgba(0,0,0,0.5)'
        }}
        aria-hidden="true"
      >
        <div className="modal-dialog">
          <form className="modal-content" onSubmit={handleSaveType}>
            <div className="modal-header">
              <h4 className="modal-title">
                {editingType ? "Edit Vehicle Type" : "Add Vehicle Type"}
              </h4>
              <button
                type="button"
                className="btn-close"
                onClick={() => {
                  setTypeModalOpen(false);
                  setEditingType(null);
                  setTypeNameInput('');
                }}
              ></button>
            </div>
            <div className="modal-body">
              <div>
                <label>Vehicle Type Name</label>
                <input
                  type="text"
                  className="form-control mt-2"
                  placeholder="Enter vehicle type (e.g. Sedan, SUV, Hatchback)"
                  value={typeNameInput}
                  onChange={(e) => setTypeNameInput(e.target.value)}
                  required
                />
              </div>
            </div>
            <div className="modal-footer">
              <button
                type="button"
                className="btn btn-white me-2"
                onClick={() => {
                  setTypeModalOpen(false);
                  setEditingType(null);
                  setTypeNameInput('');
                }}
              >
                Cancel
              </button>
              <button type="submit" className="btn btn-color" disabled={savingType}>
                {savingType ? "Saving..." : editingType ? "Update" : "Save"}
              </button>
            </div>
          </form>
        </div>
      </div>

      {/* --- Modal: Add / Edit Vehicle Color --- */}
      <div
        className={`modal fade common-modal report-modal ${colorModalOpen ? 'show' : ''}`}
        data-bs-backdrop="static"
        tabIndex={-1}
        role={colorModalOpen ? 'dialog' : ''}
        style={{
          display: colorModalOpen ? 'block' : 'none',
          backgroundColor: 'rgba(0,0,0,0.5)'
        }}
        aria-hidden="true"
      >
        <div className="modal-dialog">
          <form className="modal-content" onSubmit={handleSaveColor}>
            <div className="modal-header">
              <h4 className="modal-title">
                {editingColor ? "Edit Vehicle Color" : "Add Vehicle Color"}
              </h4>
              <button
                type="button"
                className="btn-close"
                onClick={() => {
                  setColorModalOpen(false);
                  setEditingColor(null);
                  setColorNameInput('');
                }}
              ></button>
            </div>
            <div className="modal-body">
              <div>
                <label>Vehicle Color Name</label>
                <input
                  type="text"
                  className="form-control mt-2"
                  placeholder="Enter vehicle color (e.g. White, Black, Silver, Red)"
                  value={colorNameInput}
                  onChange={(e) => setColorNameInput(e.target.value)}
                  required
                />
              </div>
            </div>
            <div className="modal-footer">
              <button
                type="button"
                className="btn btn-white me-2"
                onClick={() => {
                  setColorModalOpen(false);
                  setEditingColor(null);
                  setColorNameInput('');
                }}
              >
                Cancel
              </button>
              <button type="submit" className="btn btn-color" disabled={savingColor}>
                {savingColor ? "Saving..." : editingColor ? "Update" : "Save"}
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  );
};

export default Vehicle;