import React from "react";
import { TripCardProps, truckAdditionalData } from "./type";
import { TimerLabel } from "../../lib/common/TimerLabel";
import Spinner from "../common/Spinner";
import { InterestSvg } from "../../assets/svg/InterestSvg";
import { InterestFillSvg } from "../../assets/svg/InterestFillSvg";
import { EyeSvg } from "../../assets/svg/EyeSvg";
import { OpenSvg } from "../../assets/svg/OpenSvg";
import ForkLiftLoading from "../../assets/svg/forklift_icon_svg";
import SteelPlatform from "../../assets/svg/steel_platform_svg";
import SmoothFlooring from "../../assets/svg/smooth_flooring_svg";
import DigitalLock from "../../assets/svg/digital_lock_svg";
import CentralLock from "../../assets/svg/central_lock_svg";
import NoBeeding from "../../assets/svg/no_beeding_svg";
import Fuel from "../../assets/svg/fuel_svg";
import Dimensions from "../../assets/svg/DimensionsSvg";
import CityLoading from "../../assets/svg/city_loading_svg";
import CityUnloading from "../../assets/svg/city_unloading_svg";
import Tarpoline from "../../assets/svg/tarpoline_svg";
import { ContainerSvg } from "../../assets/svg/ContainerSvg";
import Hooks from "../../assets/svg/hooks_svg";
import GPSRequired from "../../assets/svg/gps_required_svg";
import { ProfileFilledSvg } from "../../assets/svg/ProfileFilledSvg";
import { StarSvg } from "../../assets/svg/StarSvg";
import constants from "../../lib/common/constants";
// Mapping of requirement types to icons
const requirementIcons: { [key: string]: JSX.Element } = {
    'Forklift Loading': <ForkLiftLoading />,
    'Steel Platform': <SteelPlatform />,
    'Hooks': <Hooks />,
    'Smooth Flooring': <SmoothFlooring />,
    'Central Lock': <CentralLock />,
    'Digital Lock': <DigitalLock />,
    'GPS required': <GPSRequired />,
    'Non - CNG': <Fuel />,
    'No Beading': <NoBeeding />,
    'Dimensions': <Dimensions />,
    'City Loading': <CityLoading />,
    'City Unloading': <CityUnloading />,
    'Tarpaulin': <Tarpoline />
};

type TagKey = "soft_pod" | "to_pay";

interface TagConfig {
  bgColor: string;
  textColor: string;
  label: string;
}

interface TagItem {
  key: TagKey;
  show: boolean;
}

export const TripCard = (props: TripCardProps) => {
    const { tripData, onClickTripCard, translatedTon, translatedStops, handleInterest, translatedTarpulin, employeeLanguages, translatedTexts } = props;
    const { id, sourceName, destinationName, truckTypeName, trafficName, materialName, ton, price, loadingUnloadingPoint, isInterested, isCreatedAtLessThan30Mins, isViewed, humanReadableCreatedAt, isInterestLoading, truck_type_group_id, is_price_per_ton, partner_price_per_ton, trip_additional_truck_requirements , isTopay, podType, softPodLabel, sourceStateCode, destinationStateCode} = tripData;
    const totalPoints = loadingUnloadingPoint?.length;

    const onClickCard = () => {
        onClickTripCard(id);
    };

    const handleInterestAndStopPropagation = (e: React.MouseEvent) => {
        e.stopPropagation();
        handleInterest(id);
    };

    const formatTruckRequirements = (req: truckAdditionalData) => {
        const requirements = [];

        if (req.truck_breadth && req.truck_height) {
            requirements.push({
                text: `${req.truck_breadth}ft x ${req.truck_height}ft`,
                icon: requirementIcons['Dimensions']
            });
        }

        if (req.additional_truck_requirements) {
            requirements.push(
                ...req.additional_truck_requirements.map(r => {
                    const requirementName = r?.name;
                    return {
                        text: requirementName || '',
                        icon: requirementName ? requirementIcons[requirementName] : null
                    };
                })
            );
        }

        if (req.tarpoline_count && req.tarpoline_count > 0) {
            requirements.push({
                text: `${translatedTarpulin} ${req.tarpoline_count} ${translatedTexts?.nos ?? "Nos"}`,
                icon: requirementIcons['Tarpaulin']
            });
        }

        return requirements;
    };

    // Use nullish coalescing to provide a default empty array if trip_additional_truck_requirements is undefined
    const requirementsList = (trip_additional_truck_requirements ?? []).flatMap(req => formatTruckRequirements(req));

    const initialRequirements = requirementsList.slice(0, 2);
    const remainingCount = requirementsList.length > 2 ? requirementsList.length - 2 : 0;
    
    const TAG_CONFIG: Record<TagKey, TagConfig> = {
      soft_pod: {
        bgColor: "#D5F0B1",
        textColor: "#2E5C0E",
        label: softPodLabel ?? "Soft POD",
      },
      to_pay: {
        bgColor: "#E6F2F8",
        textColor: "#003072",
        label: translatedTexts?.toPay ?? "To-Pay",
      },
    };
    
    const tags: TagItem[] = [
      { key: "soft_pod", show: podType === constants.POD_TYPE.NO_POD || podType === constants.POD_TYPE.SOFT_POD },
      { key: "to_pay", show: isTopay },
    ];
    
    const visibleTags = tags.filter(tag => tag.show);
    
    return (
        <div className="fr-trip-card fr-p-4" onClick={onClickCard}>
            <div className="fr-flex fr-items-center fr-justify-between">
                <div className="fr-flex">
                    {truck_type_group_id === 1 ? <OpenSvg className={"fr-pr-1"} /> : (truck_type_group_id === 2 ? <ContainerSvg className={"fr-pr-1"} /> : null)}
                    <div className="fr-flex fr-items-center fr-flex-wrap">
                        <p className="fr-p-style-override fr-text-sm-override fr-font-regular">
                            {truckTypeName}
                        </p>
                        <div className="fr-flex fr-items-center">
                            <span className="fr-p-style-override fr-text-sm-override fr-font-size-11 fr-font-regular fr-mx-1">
                                &nbsp;|&nbsp;
                            </span>
                            {isCreatedAtLessThan30Mins ? (
                                <span className="fr-bg-success fr-text-center fr-text-white fr-text-sm fr-font-semibold fr-px-1 fr-rounded-sm">
                                    {translatedTexts?.newLabel ?? "New"}
                                </span>
                            ) : (
                                <span className="fr-text-xs fr-text-medium-shade">
                                    {humanReadableCreatedAt}
                                </span>
                            )}
                            {isViewed ? (
                                <span className="fr-flex fr-items-center fr-text-xs fr-text-medium-shade fr-ml-1 fr-bg-gray-200">
                                    <EyeSvg className="fr-mr-1" />
                                    {translatedTexts?.viewedLabel ?? "Viewed"}
                                </span>
                            ) : null}
                        </div>
                    </div>
                </div>
                {ton ? (
                    <div className="fr-flex fr-ml-2">
                        <span className="fr-font-size-8 fr-text-xs">
                            {ton}
                        </span>
                        <span className="fr-font-size-8 fr-text-xs fr-ml-1">
                            {translatedTon}
                        </span>
                    </div>
                ) : null}
            </div>

            <div className="fr-flex fr-justify-between fr-items-center fr-my-1">
                <p className="fr-flex fr-p-style-override fr-text-medium-shade fr-font-size-11 fr-font-regular">
                    {materialName}
                    <><span className="fr-p-style-override fr-text-medium-shade fr-text-sm-override fr-font-regular">&nbsp;|&nbsp;</span>{trafficName}</>
                </p>
                <span className={`fr-font-md ${price <= 0 ? 'fr-invisible' : ''}`}>
                    ₹{is_price_per_ton ? (
                        <>
                            {partner_price_per_ton}/<span style={{ fontSize: '0.8em' }}>{translatedTon ?? "Ton"}</span>
                        </>
                    ) : (
                        price
                    )}
                </span>
            </div>
            <div className="fr-flex fr-flex-col">
                <div style={{ display: "block" }}>
                    <TimerLabel item={sourceName} dotColor="loading" dotNumber={1} stateCode={sourceStateCode} />
                    <div className="fr-timer-connector"></div>
                    {totalPoints === 3 ? (
                        <TimerLabel item={loadingUnloadingPoint[1]?.cityName} dotColor={"stops"} dotNumber={2} />
                    ) : totalPoints > 3 ? (
                        <div className="fr-flex fr-gap-4 fr-items-center">
                            <span className="fr-w-2 fr-h-2 fr-rounded-full fr-bg-primary fr-inline-block fr-ml-1"></span>
                            <p className="fr-text-sm fr-text-medium-shade fr-font-regular">{loadingUnloadingPoint?.length - 2} {translatedStops}</p>
                        </div>
                    ) : null}
                    {totalPoints > 2 ? <div className="fr-timer-connector"></div> : <></>}
                    <div className="fr-flex fr-justify-between">
  <div className="fr-flex fr-flex-col">
                        <TimerLabel
                            item={destinationName}
                            dotColor="unloading"
                            dotNumber={totalPoints ? totalPoints : 2}
                            stateCode={destinationStateCode}
                        />

    {/* ✅ Tags shown directly under destination name */}
    {visibleTags.length > 0 ? (
      <div
        style={{
          display: "flex",
          gap: "6px",
          alignItems: "center",
          marginTop: "4px",
        }}
      >
        {visibleTags.map((tag, index) => {
          const config = TAG_CONFIG[tag.key];
          if (!config) return null;
          return (
            <span
              key={index}
              style={{
                fontSize: "11px",
                fontWeight: 500,
                padding: "2px 8px",
                borderRadius: "12px",
                backgroundColor: config.bgColor,
                color: config.textColor,
                whiteSpace: "nowrap",
              }}
            >
              {config.label}
            </span>
          );
        })}
      </div>
    ) : (
      // ✅ If no tags, remove gap — keeps price aligned
      <div style={{ marginTop: "0px", height: "0px" }} />
    )}
  </div>
                        <div className="fr-flex fr-items-end fr-align-bottom">
                            <div className={`fr-flex fr-m-0 fr-cursor-pointer fr-rounded-md`} onClick={(isInterested || isInterestLoading) ? undefined : handleInterestAndStopPropagation}>
                                {
                                    isInterestLoading ? <Spinner /> :
                                        isInterested ? <InterestFillSvg size={'30'} /> : <InterestSvg size={'30'} />
                                }
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {requirementsList.length > 0 && (
                <div
                    className="fr-flex fr-items-center fr-flex-nowrap fr-gap-1 fr-mt-0"
                    style={{
                        whiteSpace: 'nowrap',
                        overflowX: 'auto',
                        overflowY: 'hidden', // Ensure vertical overflow is hidden
                        maxHeight: '100%',   // Adjust based on your needs
                    }}
                >
                    {requirementsList.length > 0 && (
                        <div
                            className="fr-flex fr-items-center fr-gap-1 fr-mt-0"
                            style={{
                                whiteSpace: 'nowrap',
                                overflowX: 'hidden',
                                overflowY: 'hidden', // Ensure vertical overflow is hidden
                            }}
                        >
                            {initialRequirements.map((item, index) => (
                                <div
                                    key={index}
                                    className="fr-flex fr-rounded-full fr-chip fr-items-center fr-gap-0"
                                    style={{
                                        padding: '2px 6px',
                                        fontSize: '6px',
                                        height: '14px',
                                        lineHeight: '14px',
                                    }}
                                >
                                    {item.icon && (
                                        <span
                                            className="fr-flex fr-items-center fr-mr-0"
                                            style={{
                                                width: '14px',
                                                height: '14px', // Adjusted to match height
                                                paddingRight: '2px',
                                                paddingLeft: '0px',
                                            }}
                                        >
                                            {item.icon}
                                        </span>
                                    )}
                                    <span
                                        className="fr-flex fr-items-center fr-text-xs"
                                        style={{
                                            paddingRight: '0px',
                                            fontSize: '6px',
                                            paddingLeft: '0px',
                                            whiteSpace: 'nowrap',
                                        }}
                                    >
                                        {
                                            item.text}
                                    </span>
                                </div>
                            ))}

                            {remainingCount > 0 && (
                                <div className="fr-flex fr-items-center fr-gap-0">
                                    <span style={{ color: '#008DD8', textDecoration: 'underline', fontSize: '9px' }}>
                                        +{remainingCount} {translatedTexts?.more ?? "more"}
                                    </span>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            )}

            <div>
            </div>
            <hr style={{ marginTop: '5px', marginBottom: '5px', color: '#f1f1f1' }} />
            <div className="flex justify-between items-center">
                <div className="flex items-center">
                    {tripData?.trafficRating ? <div style={{ position: "relative", display: "inline-block" }}>
                        {/* Profile Icon */}
                        <ProfileFilledSvg />

                        {/* Rating Badge */}
                        {tripData?.trafficRating === 'No Rating' ?
                            <div
                                style={{
                                    position: "absolute",
                                    bottom: 0,
                                    left: "50%",
                                    transform: "translate(-50%, 70%)",
                                    display: "inline-flex",
                                    alignItems: "center",
                                    lineHeight: "1",
                                    whiteSpace: "nowrap", // 👈 keeps "No Rating" in one line
                                    zIndex: 10,
                                }}
                            >
                                <span style={{ fontSize: "9px", marginTop: '2px' }}>{translatedTexts?.noRating ?? "No Rating"}</span>
                            </div>
                            :
                            <div
                                style={{
                                  position: "absolute",
                                  bottom: 0,
                                  left: "50%",
                                  transform: "translate(-50%, 70%)",
                                  display: "inline-flex",
                                  alignItems: "center",
                                  lineHeight: "1",
                                  whiteSpace: "nowrap",
                                  zIndex: 10, 
                                  border: "1px solid #ccc",
                                  borderRadius: "12px",
                                  padding: "1px 3px",
                                  background: "#fff",       
                                }}
                            >
                                <span style={{ fontSize: "9px" }}>{tripData?.trafficRating}</span>
                                <StarSvg />
                            </div>}
                    </div> : <ProfileFilledSvg />}


                    <div style={tripData?.trafficRating ? { marginLeft: '3px', marginTop: '3px' } : { paddingLeft: '2px' }}>
                        <p className="fr-text-medium-shade" style={{ fontSize: '8px', fontWeight: 'lighter' }}>{translatedTexts.trafficAgent}</p>
                        <p style={{ fontWeight: 'normal', fontSize: '10px' }}>{tripData.trafficName}</p>
                    </div>
                </div>

                {employeeLanguages && employeeLanguages.filter((lang) => lang).length > 0 && (
                    <div className="flex space-x-1" style={{ justifySelf: 'flex-end' }}>
                        <span className="fr-text-medium-shade" style={{ fontSize: '11px', fontWeight: 'lighter' }}>
                            {translatedTexts.speaks}
                        </span>
                        {employeeLanguages.slice(0, 2).map((lang: string, index: number) => (
                            <span key={index} style={{ fontSize: '11px', fontWeight: 'lighter' }}>
                                {lang}{index < employeeLanguages.slice(0, 2).length - 1 ? ',' : ''}
                            </span>
                        ))}
                        {employeeLanguages.length > 2 && (
                            <span style={{ fontSize: '9px', fontWeight: 'lighter', textDecoration: 'underline', color: '#008dd8' }}>
                                +{employeeLanguages.length - 2} {translatedTexts?.more ?? "more"}
                            </span>
                        )}
                    </div>
                )}
            </div>
        </div>

    );
};

export default TripCard;
