"use client";

import { Connector } from "@/types/connector/connector";
import React, { useState } from "react";
import {
  formatCurrency,
  formatPriceComponent,
  getPriceComponentsArray,
  toPerMinuteRateDisplay,
} from "../../connectorModule/helper";

type RateComponentInput = {
  id?: string | number;
  [key: string]: unknown;
};

const formatPriceComponentPerMinute = (component: RateComponentInput, currency = "IDR") => {
  const priceComponent = formatPriceComponent(component, currency);
  const totalPrice = priceComponent.price + (priceComponent.price * priceComponent.tax) / 100;
  const display = toPerMinuteRateDisplay(priceComponent.type, totalPrice, priceComponent.unit);

  if (display.unitPrice === totalPrice) return priceComponent;

  return {
    ...priceComponent,
    formattedPrice: formatCurrency(display.unitPrice, currency),
    unit: `/${display.unit}`,
  };
};

export function ConnectorRatesInline({
  connector,
  initiallyOpen = false,
}: Readonly<{ connector: Connector; initiallyOpen?: boolean }>) {
  const [open, setOpen] = useState<boolean>(initiallyOpen);
  const [openIdleTooltipId, setOpenIdleTooltipId] = useState<string | number | null>(null);
  if (!connector.rate) return null;
  const priceComponents = getPriceComponentsArray(connector.rate);
  return (
    <div className="mt-2">
      <button
        type="button"
        onClick={(e) => {
          e.stopPropagation();
          setOpen((v) => !v);
        }}
        className="w-full flex items-center justify-between rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-4 py-2 text-left hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
        aria-expanded={open}
      >
        <span className="text-sm font-semibold text-gray-800 dark:text-gray-100">
          Charging Rates
        </span>
        <svg
          className={`h-4 w-4 text-gray-600 dark:text-gray-300 transition-transform ${open ? "rotate-180" : ""}`}
          viewBox="0 0 20 20"
          fill="currentColor"
          aria-hidden="true"
        >
          <path
            fillRule="evenodd"
            d="M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.25a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z"
            clipRule="evenodd"
          />
        </svg>
      </button>
      {open && (
        <div className="mt-3 rounded-2xl border border-gray-100 bg-gray-50 p-4 shadow-sm dark:border-gray-700 dark:bg-gray-800">
          <div className="mb-3 flex items-center justify-between gap-3">
            <div>
              <span className="text-sm font-semibold text-gray-700 dark:text-gray-200">
                Price details
              </span>
              {connector.rate.name && (
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  {connector.rate.name}
                </p>
              )}
            </div>
            <span className="rounded-full bg-white px-2.5 py-1 text-xs font-semibold uppercase text-brand-700 ring-1 ring-gray-200 dark:bg-gray-900 dark:text-brand-200 dark:ring-gray-700">
              {connector.rate.currency}
            </span>
          </div>
          {priceComponents.length > 0 && (
            <div className="space-y-3">
              {priceComponents.map((component: RateComponentInput, index: number) => {
                const formattedComponent = formatPriceComponentPerMinute(
                  component,
                  connector.rate.currency,
                );
                const { label, formattedPrice, unit, tax, grace_period, type } = formattedComponent;
                const isIdleRate = type === "IDLE";
                const isDynamicFlatFee = type === "FLAT";
                const tooltipKey = component.id ?? index;
                return (
                  <div
                    key={component.id || index}
                    className="bg-white dark:bg-gray-900/40 p-3 rounded-xl shadow-sm"
                  >
                    <div className="flex justify-between gap-3">
                      <div className="space-y-1">
                        <div className="font-medium text-gray-900 dark:text-gray-100 flex items-center">
                          <span className="text-brand-600 dark:text-brand-300">{label}</span>
                          {isIdleRate && grace_period > 0 && (
                            <span className="relative ml-2 inline-flex">
                              <button
                                type="button"
                                aria-label="Idle fee info"
                                onClick={(event) => {
                                  event.stopPropagation();
                                  setOpenIdleTooltipId((current) =>
                                    current === tooltipKey ? null : tooltipKey,
                                  );
                                }}
                                onBlur={() => setOpenIdleTooltipId(null)}
                                className="flex h-4 w-4 items-center justify-center rounded-full border border-gray-300 text-[10px] font-bold text-gray-600 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-800"
                              >
                                ?
                              </button>
                              {openIdleTooltipId === tooltipKey && (
                                <span className="absolute left-1/2 top-full z-10 mt-2 w-56 max-w-[80vw] -translate-x-1/2 rounded-lg bg-gray-900 px-3 py-2 text-xs text-white shadow-lg whitespace-normal max-sm:left-0 max-sm:right-auto max-sm:translate-x-0 max-sm:max-w-[70vw]">
                                  Idle fees will start {grace_period} minutes after charging stops
                                </span>
                              )}
                            </span>
                          )}
                        </div>
                        <div className="text-xs text-gray-500 dark:text-gray-400 pl-1">{type}</div>
                      </div>
                      {!isDynamicFlatFee && (
                        <div className="text-right">
                          <div className="font-semibold text-brand-700 dark:text-brand-200">
                            {formattedPrice}
                            {unit && <span className="text-sm ml-1">{unit}</span>}
                          </div>
                          {tax > 0 && (
                            <span className="text-xs text-brand-500 dark:text-brand-300">
                              +{tax.toFixed(1)}% tax
                            </span>
                          )}
                        </div>
                      )}
                    </div>
                    {isDynamicFlatFee && formattedComponent.dynamicFlatFeePricing && (
                      <div className="mt-3 rounded-xl border border-brand-200 bg-brand-50 px-3 py-3 dark:border-brand-800 dark:bg-brand-900/20">
                        <p className="text-sm font-semibold leading-5 text-gray-800 dark:text-gray-100">
                          {formattedComponent.dynamicFlatFeePricing.description}
                        </p>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
          {connector.rate.minimum_amount > 0 && (
            <div className="border-t border-gray-200 dark:border-gray-700 mt-4 pt-3">
              <div className="flex justify-between items-center text-sm">
                <span className="text-gray-600 dark:text-gray-300">Minimum Amount</span>
                <span className="font-semibold text-brand-700 dark:text-brand-300">
                  {new Intl.NumberFormat("id-ID", {
                    style: "currency",
                    currency: connector.rate.currency,
                    minimumFractionDigits: 0,
                  }).format(connector.rate.minimum_amount)}
                </span>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

interface ConnectorDetailsProps {
  connector: Connector;
  selectedConnector: string | null;
  setSelectedConnector: (id: string | null) => void;
  isConnectorSelectable: (connector: Connector) => boolean;
  isMobile?: boolean;
  online?: boolean;
  showRates?: boolean; // whether to render rates inside this component (desktop true, modal false)
  childrenAfterActions?: React.ReactNode; // content to render right after the action buttons, before rates
}

const ConnectorDetails = ({
  connector,
  selectedConnector,
  setSelectedConnector,
  isConnectorSelectable,
  isMobile = false,
  online = false,
  showRates = true,
  childrenAfterActions,
}: ConnectorDetailsProps) => (
  <div className={`${isMobile ? "" : "border-t pt-4"} space-y-4`}>
    {/* Description */}
    {connector.description && connector.description !== "-" && (
      <div>
        <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">Description</h4>
        <p className="text-sm text-gray-600 dark:text-gray-400">{connector.description}</p>
      </div>
    )}

    {/* Action Buttons (Desktop only) */}
    {!isMobile && (
      <div className="flex gap-3 pt-2">
        {isConnectorSelectable(connector) ? (
          <>
            <button
              onClick={(e) => {
                e.stopPropagation();
                if (!isConnectorSelectable(connector)) return;
                setSelectedConnector(selectedConnector === connector.id ? null : connector.id!);
              }}
              className={`
                flex-1 rounded-lg px-4 py-2 font-medium transition-colors
                ${
                  selectedConnector === connector.id
                    ? "bg-red-600 text-white hover:bg-red-700"
                    : "bg-brand-600 text-white hover:bg-brand-700 active:bg-brand-800"
                }
              `}
            >
              {selectedConnector === connector.id ? "Unselect" : "Select Connector"}
            </button>
          </>
        ) : (
          (() => {
            let statusLabel: string;
            if (!online) {
              statusLabel = "Station offline";
            } else if (connector.status === "Charging") {
              statusLabel = "Currently in use";
            } else {
              statusLabel = `Unavailable (${connector.status})`;
            }
            return (
              <div className="flex-1 rounded-lg px-4 py-2 font-medium bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400 text-center">
                {statusLabel}
              </div>
            );
          })()
        )}
      </div>
    )}

    {/* Custom content right after actions (e.g., Connect button), before rates */}
    {childrenAfterActions}

    {/* Rates moved after action buttons (optional render) */}
    {showRates && <ConnectorRatesInline connector={connector} />}
  </div>
);

export default ConnectorDetails;
