"use client";

import { PageLayout } from "@/components/templates/PageLayout";
import { Button } from "@/components/atoms/button";
import { AnimatedCard } from "@/components/molecules";
import { AddonGroup } from "@/features/catalog/components/base/AddonGroup";
import { StepHeader } from "@/components/atoms";
import { SimTypeSelector } from "@/features/catalog/components/sim/SimTypeSelector";
import { ActivationForm } from "@/features/catalog/components/sim/ActivationForm";
import { MnpForm } from "@/features/catalog/components/sim/MnpForm";
import { ProgressSteps } from "@/components/molecules";
import { CatalogBackLink } from "@/features/catalog/components/base/CatalogBackLink";
import {
  ArrowLeftIcon,
  ArrowRightIcon,
  DevicePhoneMobileIcon,
  ExclamationTriangleIcon,
  UsersIcon,
} from "@heroicons/react/24/outline";
import type { UseSimConfigureResult } from "@/features/catalog/hooks/useSimConfigure";
import type { SimActivationFeeCatalogItem } from "@customer-portal/domain/catalog";

type Props = UseSimConfigureResult & {
  onConfirm: () => void;
};

export function SimConfigureView({
  plan,
  activationFees,
  addons,
  loading,
  simType,
  setSimType,
  eid,
  setEid,
  selectedAddons,
  setSelectedAddons,
  activationType,
  setActivationType,
  scheduledActivationDate,
  setScheduledActivationDate,
  wantsMnp,
  setWantsMnp,
  mnpData,
  setMnpData,
  validate,
  currentStep,
  setCurrentStep,
  onConfirm,
}: Props) {
  const getRequiredActivationFee = (
    fees: SimActivationFeeCatalogItem[]
  ): SimActivationFeeCatalogItem | undefined => {
    if (!Array.isArray(fees) || fees.length === 0) {
      return undefined;
    }
    return (
      fees.find(fee => fee.catalogMetadata?.autoAdd) ||
      fees.find(fee => fee.catalogMetadata?.isDefault) ||
      fees[0]
    );
  };

  const resolveOneTimeCharge = (value?: {
    oneTimePrice?: number;
    unitPrice?: number;
    monthlyPrice?: number;
  }): number => {
    if (!value) return 0;
    return value.oneTimePrice ?? value.unitPrice ?? value.monthlyPrice ?? 0;
  };

  const requiredActivationFee = getRequiredActivationFee(activationFees);
  const activationFeeAmount = resolveOneTimeCharge(requiredActivationFee);
  const activationFeeDetails =
    requiredActivationFee && activationFeeAmount > 0
      ? {
          name: requiredActivationFee.name,
          amount: activationFeeAmount,
        }
      : undefined;

  // Calculate display totals from catalog prices (for display only)
  // Note: BFF will recalculate authoritative pricing
  const monthlyTotal =
    (plan?.monthlyPrice ?? 0) +
    selectedAddons.reduce((sum, addonSku) => {
      const addon = addons.find(a => a.sku === addonSku);
      return sum + (addon?.monthlyPrice ?? 0);
    }, 0);

  const oneTimeTotal =
    (plan?.oneTimePrice ?? 0) +
    activationFeeAmount +
    selectedAddons.reduce((sum, addonSku) => {
      const addon = addons.find(a => a.sku === addonSku);
      return sum + (addon?.oneTimePrice ?? 0);
    }, 0);

  if (loading) {
    return (
      <PageLayout
        title="Configure SIM"
        description="Customize your mobile service"
        icon={<DevicePhoneMobileIcon className="h-6 w-6" />}
      >
        <div className="max-w-4xl mx-auto space-y-8">
          {/* Header card skeleton */}
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <div className="flex justify-between items-start">
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <div className="h-5 w-5 bg-blue-200 rounded" />
                  <div className="h-5 w-48 bg-gray-200 rounded" />
                  <div className="h-5 w-24 bg-green-100 rounded-full" />
                </div>
                <div className="flex items-center gap-4">
                  <div className="h-4 w-24 bg-gray-200 rounded" />
                  <div className="h-4 w-28 bg-gray-200 rounded" />
                </div>
              </div>
              <div className="text-right space-y-2">
                <div className="h-7 w-24 bg-blue-200 rounded" />
                <div className="h-4 w-28 bg-green-100 rounded" />
              </div>
            </div>
          </div>

          {/* Steps indicator */}
          <div className="flex items-center justify-between max-w-2xl mx-auto">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="flex-1 flex items-center">
                <div className="h-3 w-3 rounded-full bg-gray-300" />
                {i < 3 && <div className="h-1 flex-1 bg-gray-200 mx-2 rounded" />}
              </div>
            ))}
          </div>

          {/* Step 1 card skeleton */}
          <div className="bg-white rounded-xl border border-gray-200 p-8">
            <div className="mb-6">
              <div className="h-5 w-48 bg-gray-200 rounded mb-2" />
              <div className="h-4 w-72 bg-gray-200 rounded" />
            </div>
            <div className="h-10 w-full bg-gray-100 rounded mb-4" />
            <div className="h-10 w-72 bg-gray-100 rounded ml-auto" />
          </div>
        </div>
      </PageLayout>
    );
  }

  if (!plan) {
    return (
      <PageLayout
        title="Plan Not Found"
        description="The selected plan could not be found"
        icon={<ExclamationTriangleIcon className="h-6 w-6" />}
      >
        <div className="text-center py-12">
          <ExclamationTriangleIcon className="h-12 w-12 mx-auto text-red-400 mb-4" />
          <h2 className="text-xl font-semibold text-gray-900 mb-2">Plan Not Found</h2>
          <p className="text-gray-600 mb-4">The selected plan could not be found</p>
          <a href="/catalog/sim" className="text-blue-600 hover:text-blue-800 font-medium">
            ← Return to SIM Plans
          </a>
        </div>
      </PageLayout>
    );
  }

  const steps = [
    { number: 1, title: "SIM Type", completed: currentStep > 1 },
    { number: 2, title: "Activation", completed: currentStep > 2 },
    { number: 3, title: "Add-ons", completed: currentStep > 3 },
    { number: 4, title: "Number Porting", completed: currentStep > 4 },
  ];

  const handleAddonSelection = (newSelectedSkus: string[]) => setSelectedAddons(newSelectedSkus);

  return (
    <PageLayout
      title={`Configure ${plan.name}`}
      description="Customize your mobile service"
      icon={<DevicePhoneMobileIcon className="h-6 w-6" />}
    >
      <div className="max-w-4xl mx-auto space-y-8">
        <CatalogBackLink href="/catalog/sim" label="Back to SIM Plans" />

        <AnimatedCard variant="static" className="p-6">
          <div className="flex justify-between items-start">
            <div>
              <div className="flex items-center gap-2 mb-2">
                <DevicePhoneMobileIcon className="h-5 w-5 text-blue-600" />
                <h3 className="font-bold text-lg text-gray-900">{plan.name}</h3>
                {plan.simHasFamilyDiscount && (
                  <span className="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full font-medium flex items-center gap-1">
                    <UsersIcon className="h-3 w-3" />
                    Family Discount
                  </span>
                )}
              </div>
              <div className="flex items-center gap-4 text-sm text-gray-600 mb-2">
                <span>
                  <strong>Data:</strong> {plan.simDataSize}
                </span>
                <span>
                  <strong>Type:</strong>{" "}
                  {plan.simPlanType === "DataSmsVoice"
                    ? "Data + SMS + Voice"
                    : plan.simPlanType === "DataOnly"
                      ? "Data Only"
                      : "Voice + SMS Only"}
                </span>
              </div>
            </div>
            <div className="text-right">
              <div className="text-2xl font-bold text-blue-600">
                ¥{(plan.monthlyPrice ?? plan.unitPrice ?? plan.oneTimePrice ?? 0).toLocaleString()}
                /mo
              </div>
              {plan.simHasFamilyDiscount && (
                <div className="text-sm text-green-600 font-medium">Discounted Price</div>
              )}
            </div>
          </div>
        </AnimatedCard>

        <ProgressSteps steps={steps} currentStep={currentStep} />

        {plan.name.toLowerCase().includes("platinum") && (
          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div className="flex items-start">
              <ExclamationTriangleIcon className="w-5 h-5 text-yellow-600 mt-0.5 flex-shrink-0" />
              <div className="ml-3">
                <h5 className="font-medium text-yellow-900">PLATINUM Plan Notice</h5>
                <p className="text-sm text-yellow-800 mt-1">
                  Additional device subscription fees may apply. Contact support for details.
                </p>
              </div>
            </div>
          </div>
        )}

        <div className="space-y-8">
          {currentStep === 1 && (
            <AnimatedCard
              variant="static"
              className={`p-8 transition-all duration-500 ease-in-out transform opacity-100 translate-y-0`}
            >
              <div className="mb-6">
                <StepHeader
                  stepNumber={1}
                  title="Select SIM Type"
                  description="Choose between eSIM and physical SIM"
                />
              </div>
              <SimTypeSelector
                simType={simType}
                onSimTypeChange={setSimType}
                eid={eid}
                onEidChange={setEid}
                errors={{}}
              />
              <div className="flex justify-end mt-6">
                <Button
                  onClick={() => {
                    if (simType === "eSIM" && !validate()) {
                      return;
                    }
                    setCurrentStep(2);
                  }}
                  rightIcon={<ArrowRightIcon className="w-4 h-4" />}
                >
                  Continue to Activation
                </Button>
              </div>
            </AnimatedCard>
          )}

          {currentStep === 2 && (
            <AnimatedCard
              variant="static"
              className={`p-8 transition-all duration-500 ease-in-out transform opacity-100 translate-y-0`}
            >
              <div className="mb-6">
                <StepHeader
                  stepNumber={2}
                  title="Activation"
                  description="Choose when to start your service"
                />
              </div>
              <ActivationForm
                activationType={activationType}
                onActivationTypeChange={setActivationType}
                scheduledActivationDate={scheduledActivationDate}
                onScheduledActivationDateChange={setScheduledActivationDate}
                errors={{}}
                activationFee={activationFeeDetails}
              />
              <div className="flex justify-between mt-6">
                <Button
                  onClick={() => setCurrentStep(1)}
                  variant="outline"
                  leftIcon={<ArrowLeftIcon className="w-4 h-4" />}
                >
                  Back to SIM Type
                </Button>
                <Button
                  onClick={() => {
                    if (activationType === "Scheduled" && !validate()) {
                      return;
                    }
                    setCurrentStep(3);
                  }}
                  rightIcon={<ArrowRightIcon className="w-4 h-4" />}
                >
                  Continue to Add-ons
                </Button>
              </div>
            </AnimatedCard>
          )}

          {currentStep === 3 && (
            <AnimatedCard
              variant="static"
              className={`p-8 transition-all duration-500 ease-in-out transform opacity-100 translate-y-0`}
            >
              <div className="mb-6">
                <StepHeader
                  stepNumber={3}
                  title="Add-ons"
                  description="Optional services to enhance your experience"
                />
              </div>
              {addons.length > 0 ? (
                <AddonGroup
                  addons={addons}
                  selectedAddonSkus={selectedAddons}
                  onAddonToggle={handleAddonSelection}
                  showSkus={false}
                />
              ) : (
                <div className="text-center py-8">
                  <p className="text-gray-600">
                    {plan.simPlanType === "DataOnly"
                      ? "No add-ons are available for data-only plans."
                      : "No add-ons are available for this plan."}
                  </p>
                </div>
              )}
              <div className="flex justify-between mt-6">
                <Button
                  onClick={() => setCurrentStep(2)}
                  variant="outline"
                  leftIcon={<ArrowLeftIcon className="w-4 h-4" />}
                >
                  Back to Activation
                </Button>
                <Button
                  onClick={() => setCurrentStep(4)}
                  rightIcon={<ArrowRightIcon className="w-4 h-4" />}
                >
                  Continue to Number Porting
                </Button>
              </div>
            </AnimatedCard>
          )}

          {currentStep === 4 && (
            <AnimatedCard
              variant="static"
              className={`p-8 transition-all duration-500 ease-in-out transform opacity-100 translate-y-0`}
            >
              <div className="mb-6">
                <StepHeader
                  stepNumber={4}
                  title="Number Porting (Optional)"
                  description="Keep your existing phone number by transferring it to your new SIM"
                />
              </div>
              <MnpForm
                wantsMnp={wantsMnp}
                onWantsMnpChange={setWantsMnp}
                mnpData={mnpData}
                onMnpDataChange={setMnpData}
                errors={{}}
              />
              <div className="flex justify-between mt-6">
                <Button
                  onClick={() => setCurrentStep(3)}
                  variant="outline"
                  leftIcon={<ArrowLeftIcon className="w-4 h-4" />}
                >
                  Back to Add-ons
                </Button>
                <Button
                  onClick={() => {
                    if ((wantsMnp || activationType === "Scheduled") && !validate()) return;
                    setCurrentStep(5);
                  }}
                  rightIcon={<ArrowRightIcon className="w-4 h-4" />}
                >
                  Review Order
                </Button>
              </div>
            </AnimatedCard>
          )}
        </div>

        {currentStep === 5 && (
          <AnimatedCard
            variant="static"
            className={`p-8 transition-all duration-500 ease-in-out transform opacity-100 translate-y-0`}
          >
            <div className="mb-6">
              <StepHeader
                stepNumber={5}
                title="Review Your Order"
                description="Review your configuration and proceed to checkout"
              />
            </div>

            <div className="max-w-lg mx-auto mb-8 bg-gradient-to-b from-white to-gray-50 shadow-xl rounded-lg border border-gray-200 p-6">
              <div className="text-center border-b-2 border-dashed border-gray-300 pb-4 mb-6">
                <h3 className="text-xl font-bold text-gray-900 mb-1">Order Summary</h3>
                <p className="text-sm text-gray-500">Review your configuration</p>
              </div>

              <div className="space-y-3 mb-6">
                <div className="flex justify-between items-start">
                  <div>
                    <h4 className="font-semibold text-gray-900">{plan.name}</h4>
                    <p className="text-sm text-gray-600">{plan.simDataSize}</p>
                  </div>
                  <div className="text-right">
                    <p className="font-semibold text-gray-900">
                      ¥{plan.monthlyPrice?.toLocaleString()}
                    </p>
                    <p className="text-xs text-gray-500">per month</p>
                  </div>
                </div>
              </div>

              <div className="border-t border-gray-200 pt-4 mb-6">
                <h4 className="font-medium text-gray-900 mb-3">Configuration</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-600">SIM Type:</span>
                    <span className="text-gray-900">{simType || "Not selected"}</span>
                  </div>
                  {simType === "eSIM" && eid && (
                    <div className="flex justify-between">
                      <span className="text-gray-600">EID:</span>
                      <span className="text-gray-900 font-mono text-xs">
                        {eid.substring(0, 12)}...
                      </span>
                    </div>
                  )}
                  <div className="flex justify-between">
                    <span className="text-gray-600">Activation:</span>
                    <span className="text-gray-900">
                      {activationType === "Scheduled" && scheduledActivationDate
                        ? `${new Date(scheduledActivationDate).toLocaleDateString("en-US", { month: "short", day: "numeric" })}`
                        : activationType || "Not selected"}
                    </span>
                  </div>
                  {wantsMnp && (
                    <div className="flex justify-between">
                      <span className="text-gray-600">Number Porting:</span>
                      <span className="text-gray-900">Requested</span>
                    </div>
                  )}
                </div>
              </div>

              {selectedAddons.length > 0 && (
                <div className="border-t border-gray-200 pt-4 mb-6">
                  <h4 className="font-medium text-gray-900 mb-3">Add-ons</h4>
                  <div className="space-y-2">
                    {selectedAddons.map(addonSku => {
                      const addon = addons.find(a => a.sku === addonSku);
                      const addonAmount = addon
                        ? addon.billingCycle === "Monthly"
                          ? (addon.monthlyPrice ?? addon.unitPrice ?? 0)
                          : (addon.oneTimePrice ?? addon.unitPrice ?? 0)
                        : 0;

                      return (
                        <div key={addonSku} className="flex justify-between text-sm">
                          <span className="text-gray-600">{addon?.name || addonSku}</span>
                          <span className="text-gray-900">
                            ¥{addonAmount.toLocaleString()}
                            <span className="text-xs text-gray-500 ml-1">
                              /{addon?.billingCycle === "Monthly" ? "mo" : "once"}
                            </span>
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {activationFeeDetails && (
                <div className="border-t border-gray-200 pt-4 mb-6">
                  <h4 className="font-medium text-gray-900 mb-3">One-time Fees</h4>
                  <div className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">{activationFeeDetails.name}</span>
                      <span className="text-gray-900">
                        ¥{activationFeeDetails.amount.toLocaleString()}
                      </span>
                    </div>
                    {(requiredActivationFee?.catalogMetadata?.autoAdd ||
                      requiredActivationFee?.catalogMetadata?.isDefault) && (
                      <p className="text-xs text-gray-500">
                        Required for all new SIM activations
                      </p>
                    )}
                  </div>
                </div>
              )}

              <div className="border-t-2 border-dashed border-gray-300 pt-4 bg-gray-50 -mx-6 px-6 py-4 rounded-b-lg">
                <div className="space-y-2">
                  <div className="flex justify-between text-xl font-bold">
                    <span className="text-gray-900">Monthly Total</span>
                    <span className="text-blue-600">¥{monthlyTotal.toLocaleString()}</span>
                  </div>
                  {oneTimeTotal > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">One-time Total</span>
                      <span className="text-orange-600 font-semibold">
                        ¥{oneTimeTotal.toLocaleString()}
                      </span>
                    </div>
                  )}
                </div>
              </div>
            </div>

            <div className="flex justify-between items-center pt-6 border-t">
              <Button
                onClick={() => setCurrentStep(4)}
                variant="outline"
                size="lg"
                className="px-8 py-4 text-lg"
                leftIcon={<ArrowLeftIcon className="w-5 h-5" />}
              >
                Back to Number Porting
              </Button>
              <Button
                onClick={onConfirm}
                size="lg"
                className="px-12 py-4 text-lg font-semibold"
                rightIcon={<ArrowRightIcon className="w-5 h-5" />}
              >
                Proceed to Checkout
              </Button>
            </div>
          </AnimatedCard>
        )}
      </div>
    </PageLayout>
  );
}
