"use client";

import { Session, CostBreakdown, IdleCostEstimate } from "@/types/session/session";
import { formatCurrency } from "@/lib/utils.client";
import { CheckCircle, AlertTriangle, X } from "lucide-react";
import Timer from "./Timer";
import { Modal } from "@/components/ui/modal";
import { resolveBreakdownLabel } from "@/modules/sessionModule/detail/utils/costBreakdown";
import { isSessionIdleOngoing } from "@/modules/sessionModule/detail/sessionDetailUtils";

interface SessionStopSuccessCardProps {
  session: Session;
  idleCostEstimate: IdleCostEstimate | null;
  onBackToSessions: () => void;
  countdown: number;
  onSkipCountdown: () => void;
  isOpen: boolean;
}

export const SessionStopSuccessCard = ({
  session,
  idleCostEstimate,
  onBackToSessions,
  countdown,
  onSkipCountdown,
  isOpen,
}: SessionStopSuccessCardProps) => {
  const status = session.status;
  const isEnded = status === "Ended";
  const isIdle = isSessionIdleOngoing(session);
  const isIdleState = isIdle;

  // Get IDLE cost breakdown
  const idleCostBreakdown =
    session.cost?.breakdown?.filter((item) => item.type.toLowerCase().includes("idle")) || [];

  const totalCost = session.cost?.amount || 0;
  const energyConsumed = (session.metrics?.energy_consumed || 0) / 1000;

  // Calculate total duration
  const startTime = session.created_at;
  const endTime = session.status === "Ended" ? session.updated_at : session.updated_at;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onBackToSessions}
      isFullscreen={true}
      showCloseButton={false}
      className="bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-950/30 dark:to-emerald-950/30 overflow-y-auto"
    >
      <div className="relative flex flex-col min-h-full w-full">
        {/* Success Background Pattern */}
        <div className="absolute inset-0 bg-green-100/50 dark:bg-green-950/20 pointer-events-none" />

        <div className="relative z-10 flex-1 flex flex-col items-center justify-center p-4 sm:p-6 lg:p-8 py-8 sm:py-12 space-y-6 sm:space-y-8 max-w-4xl mx-auto w-full">
          {/* Success Header */}
          <div className="text-center space-y-4 animate-in fade-in slide-in-from-top-4 duration-500">
            <div className="flex justify-center">
              <div className="rounded-full bg-green-500 dark:bg-green-600 p-4 sm:p-5 animate-pulse">
                <CheckCircle className="w-10 h-10 sm:w-12 sm:h-12 text-white" fill="currentColor" />
              </div>
            </div>
            <h3 className="text-3xl sm:text-4xl font-bold text-gray-900 dark:text-white">
              Charging Session Stopped
            </h3>
            <p className="text-base sm:text-lg text-gray-600 dark:text-gray-400">
              Your session has been successfully stopped
            </p>
          </div>

          {/* Status Badge */}
          <div className="flex justify-center animate-in fade-in duration-500 delay-100">
            {isIdleState ? (
              <div className="inline-flex items-center gap-2 rounded-full px-5 py-2.5 bg-orange-100 dark:bg-orange-900/30 border-2 border-orange-300 dark:border-orange-700">
                <AlertTriangle className="w-5 h-5 sm:w-6 sm:h-6 text-orange-600 dark:text-orange-400" />
                <span className="text-sm sm:text-base font-semibold text-orange-800 dark:text-orange-300">
                  IDLE Status
                </span>
              </div>
            ) : (
              <div className="inline-flex items-center gap-2 rounded-full px-5 py-2.5 bg-green-100 dark:bg-green-900/30 border-2 border-green-300 dark:border-green-700">
                <CheckCircle className="w-5 h-5 sm:w-6 sm:h-6 text-green-600 dark:text-green-400" />
                <span className="text-sm sm:text-base font-semibold text-green-800 dark:text-green-300">
                  Session Ended
                </span>
              </div>
            )}
          </div>

          {/* Final Metrics */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 sm:gap-6 w-full animate-in fade-in duration-500 delay-200">
            {/* Total Cost */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 sm:p-6 border border-gray-200 dark:border-gray-700 shadow-md hover:shadow-lg transition-shadow">
              <p className="text-xs sm:text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">
                Total Cost
              </p>
              <p className="text-3xl sm:text-4xl font-bold text-green-600 dark:text-green-400">
                {formatCurrency(totalCost)}
              </p>
              {session.cost?.currency && (
                <p className="text-xs text-gray-400 dark:text-gray-500 mt-2">
                  {session.cost.currency}
                </p>
              )}
            </div>

            {/* Total Duration */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 sm:p-6 border border-gray-200 dark:border-gray-700 shadow-md hover:shadow-lg transition-shadow">
              <p className="text-xs sm:text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">
                Total Duration
              </p>
              <div className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-white">
                <Timer startTime={startTime} endTime={endTime} />
              </div>
            </div>

            {/* Energy Consumed */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-5 sm:p-6 border border-gray-200 dark:border-gray-700 shadow-md hover:shadow-lg transition-shadow">
              <p className="text-xs sm:text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">
                Energy Consumed
              </p>
              <p className="text-3xl sm:text-4xl font-bold text-gray-900 dark:text-white">
                {energyConsumed.toFixed(2)} kWh
              </p>
            </div>
          </div>

          {/* IDLE Warning Section */}
          {isIdleState && (
            <div className="bg-orange-50 dark:bg-orange-900/20 rounded-xl p-5 sm:p-6 border-2 border-orange-200 dark:border-orange-800 w-full animate-in fade-in duration-500 delay-300">
              <div className="flex items-start gap-4">
                <AlertTriangle className="w-6 h-6 sm:w-7 sm:h-7 text-orange-600 dark:text-orange-400 flex-shrink-0 mt-0.5" />
                <div className="flex-1 space-y-3">
                  <p className="text-base sm:text-lg font-semibold text-orange-900 dark:text-orange-200">
                    IDLE Cost Warning
                  </p>
                  <p className="text-sm text-orange-700 dark:text-orange-300">
                    Your session is in IDLE status. Additional costs may apply.
                  </p>
                  <div className="mt-3 space-y-2">
                    {idleCostBreakdown.map((item: CostBreakdown, index: number) => (
                      <div
                        key={`${item.type}-${index}`}
                        className="flex items-center justify-between text-sm"
                      >
                        <span className="text-orange-700 dark:text-orange-300">
                          {resolveBreakdownLabel(item, undefined, {
                            rateFees: session.fee_details?.rate_fees,
                            breakdown: idleCostBreakdown,
                            index,
                          })}
                        </span>
                        <span className="font-semibold text-orange-900 dark:text-orange-200">
                          {formatCurrency(item.unit_price)}/{item.unit || "hour"}
                        </span>
                      </div>
                    ))}
                    <div className="flex items-center justify-between pt-3 mt-3 border-t border-orange-200 dark:border-orange-800">
                      <span className="text-base font-semibold text-orange-900 dark:text-orange-200">
                        Current IDLE Cost (Est.)
                      </span>
                      <span className="text-base font-bold text-orange-900 dark:text-orange-200">
                        {idleCostEstimate
                          ? formatCurrency(idleCostEstimate.amount)
                          : "Calculating…"}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Countdown and Actions */}
          <div className="flex flex-col sm:flex-row items-center justify-between gap-4 sm:gap-6 pt-6 sm:pt-8 border-t-2 border-green-200 dark:border-green-800 w-full animate-in fade-in duration-500 delay-400">
            {/* Countdown */}
            {countdown > 0 && (
              <div className="flex items-center gap-3 text-base sm:text-lg text-gray-600 dark:text-gray-400">
                <span>Redirecting in</span>
                <span className="font-mono font-bold text-2xl text-green-600 dark:text-green-400">
                  {countdown}s
                </span>
                <button
                  onClick={onSkipCountdown}
                  className="ml-2 px-3 py-2 min-h-[40px] min-w-[40px] text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 touch-manipulation"
                  aria-label="Skip countdown"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            )}

            {/* Action Button */}
            <button
              onClick={onBackToSessions}
              className="w-full sm:w-auto px-8 py-4 min-h-[52px] bg-green-600 hover:bg-green-700 active:bg-green-800 text-white text-base sm:text-lg font-semibold rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl active:scale-95 dark:bg-green-500 dark:hover:bg-green-600 dark:active:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 touch-manipulation"
              aria-label="Back to sessions list"
            >
              Back to Sessions
            </button>
          </div>
        </div>
      </div>
    </Modal>
  );
};
