"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { PageLayout } from "@/components/templates/PageLayout";
import { SubCard } from "@/components/molecules/SubCard/SubCard";
import { DevicePhoneMobileIcon, DeviceTabletIcon, CpuChipIcon } from "@heroicons/react/24/outline";
import { simActionsService } from "@/features/subscriptions/api/sim-actions.api";
import type { SimReissueFullRequest } from "@customer-portal/domain/sim";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import type { SimDetails } from "@/features/subscriptions/components/sim/SimDetailsCard";
import { Button } from "@/components/atoms";
import { devErrorMessage } from "@/shared/utils";

type SimType = "physical" | "esim";

const CHECK_PATH =
  "M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z";

function SelectedCheckmark() {
  return (
    <div className="absolute top-2 right-2 w-6 h-6 bg-primary rounded-full flex items-center justify-center">
      <svg className="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
        <path fillRule="evenodd" d={CHECK_PATH} clipRule="evenodd" />
      </svg>
    </div>
  );
}

function CurrentSimInfo({
  simDetails,
  currentEid,
}: {
  simDetails: SimDetails;
  currentEid: string | null;
}) {
  return (
    <div className="bg-muted border border-border rounded-lg p-4 mb-6">
      <div className="text-xs text-muted-foreground font-medium uppercase mb-2">Current SIM</div>
      <div className="grid grid-cols-2 gap-4 text-sm">
        <div>
          <span className="text-muted-foreground">Number:</span>{" "}
          <span className="font-medium">{simDetails.msisdn}</span>
        </div>
        <div>
          <span className="text-muted-foreground">Type:</span>{" "}
          <span className="font-medium capitalize">{simDetails.simType}</span>
        </div>
        {simDetails.iccid && (
          <div className="col-span-2">
            <span className="text-muted-foreground">ICCID:</span>{" "}
            <span className="font-mono text-xs">{simDetails.iccid}</span>
          </div>
        )}
        {currentEid && (
          <div className="col-span-2">
            <span className="text-muted-foreground">Current EID:</span>{" "}
            <span className="font-mono text-xs">{currentEid}</span>
          </div>
        )}
      </div>
    </div>
  );
}

function SimTypeOption({
  value,
  selected,
  onSelect,
  icon: Icon,
  label,
  description,
}: {
  value: SimType;
  selected: boolean;
  onSelect: () => void;
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  description: string;
}) {
  return (
    <label
      className={`relative flex flex-col items-center p-6 border-2 rounded-xl cursor-pointer transition-all ${
        selected
          ? "border-primary bg-primary-soft"
          : "border-border hover:border-border-muted bg-card"
      }`}
    >
      <input
        type="radio"
        name="simType"
        value={value}
        checked={selected}
        onChange={onSelect}
        className="sr-only"
      />
      <Icon className="h-12 w-12 text-muted-foreground mb-3" />
      <div className="text-lg font-medium text-foreground">{label}</div>
      <div className="text-sm text-muted-foreground text-center mt-1">{description}</div>
      {selected && <SelectedCheckmark />}
    </label>
  );
}

function EsimEidInput({
  newEid,
  onEidChange,
  isValidEid,
  currentEid,
}: {
  newEid: string;
  onEidChange: (value: string) => void;
  isValidEid: boolean;
  currentEid: string | null;
}) {
  return (
    <div className="space-y-4 p-4 bg-info-soft border border-info/25 rounded-lg">
      <div>
        <label className="block text-sm font-medium text-foreground mb-2">
          New EID (eSIM Identifier)
        </label>
        <input
          type="text"
          value={newEid}
          onChange={e => onEidChange(e.target.value.replace(/\D/g, ""))}
          placeholder="Enter your device's 32-digit EID"
          maxLength={32}
          className="w-full px-3 py-2 border border-input rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring font-mono bg-background text-foreground"
        />
        <p className="text-xs text-muted-foreground mt-1">
          The EID is a 32-digit number unique to your device. You can find it in your device
          settings under &quot;About&quot; or &quot;SIM status&quot;.
        </p>
        {newEid && !isValidEid && (
          <p className="text-xs text-danger mt-1">
            Please enter exactly 32 digits ({newEid.length}/32)
          </p>
        )}
      </div>
      {currentEid && (
        <div className="text-sm text-foreground">
          <strong>Current EID:</strong> <span className="font-mono text-xs">{currentEid}</span>
        </div>
      )}
    </div>
  );
}

function useSimReissueState(subscriptionId: string) {
  const [simType, setSimType] = useState<SimType | null>(null);
  const [newEid, setNewEid] = useState("");
  const [currentEid, setCurrentEid] = useState<string | null>(null);
  const [simDetails, setSimDetails] = useState<SimDetails | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [loadingDetails, setLoadingDetails] = useState(true);

  useEffect(() => {
    const fetchDetails = async () => {
      try {
        const info = await simActionsService.getSimInfo(subscriptionId);
        if (info?.details) {
          setSimDetails(info.details);
          setCurrentEid(info.details.eid || null);
        }
      } catch (e: unknown) {
        setError(
          devErrorMessage(
            e,
            "Failed to load SIM details",
            "Unable to load SIM details right now. Please try again."
          )
        );
      } finally {
        setLoadingDetails(false);
      }
    };
    void fetchDetails();
  }, [subscriptionId]);

  const isValidEid = /^\d{32}$/.test(newEid.trim());

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!simType) {
      setError("Please select a SIM type");
      return;
    }
    if (simType === "esim" && !isValidEid) {
      setError("Please enter a valid 32-digit EID");
      return;
    }
    setLoading(true);
    setMessage(null);
    setError(null);
    try {
      const request: SimReissueFullRequest =
        simType === "esim" ? { simType, newEid: newEid.trim() } : { simType };
      await simActionsService.reissueSim(subscriptionId, request);
      setMessage(
        simType === "esim"
          ? "eSIM reissue request submitted successfully. You will receive instructions via email to download your new eSIM profile."
          : "Physical SIM reissue request submitted successfully. You will be contacted shortly with shipping details (typically 3-5 business days)."
      );
    } catch (e: unknown) {
      setError(
        devErrorMessage(
          e,
          "Failed to submit reissue request",
          "Unable to submit your request right now. Please try again."
        )
      );
    } finally {
      setLoading(false);
    }
  };

  return {
    simType,
    setSimType,
    newEid,
    setNewEid,
    currentEid,
    simDetails,
    message,
    error,
    loading,
    loadingDetails,
    isValidEid,
    submit,
  };
}

function ReissueForm({
  state,
  subscriptionId,
}: {
  state: ReturnType<typeof useSimReissueState>;
  subscriptionId: string;
}) {
  const {
    simType,
    setSimType,
    newEid,
    setNewEid,
    currentEid,
    simDetails,
    isValidEid,
    loading,
    submit,
  } = state;

  return (
    <form onSubmit={e => void submit(e)} className="space-y-6">
      {simDetails && <CurrentSimInfo simDetails={simDetails} currentEid={currentEid} />}

      <div className="space-y-3">
        <label className="block text-sm font-medium text-muted-foreground">
          Select Replacement SIM Type
        </label>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <SimTypeOption
            value="physical"
            selected={simType === "physical"}
            onSelect={() => setSimType("physical")}
            icon={DeviceTabletIcon}
            label="Physical SIM"
            description="A new physical SIM card will be shipped to you"
          />
          <SimTypeOption
            value="esim"
            selected={simType === "esim"}
            onSelect={() => setSimType("esim")}
            icon={CpuChipIcon}
            label="eSIM"
            description="Download your eSIM profile instantly"
          />
        </div>
      </div>

      {simType === "esim" && (
        <EsimEidInput
          newEid={newEid}
          onEidChange={setNewEid}
          isValidEid={isValidEid}
          currentEid={currentEid}
        />
      )}

      {simType === "physical" && (
        <div className="p-4 bg-warning-soft border border-warning/25 rounded-lg">
          <h3 className="text-sm font-medium text-foreground mb-2">Physical SIM Information</h3>
          <ul className="text-sm text-muted-foreground space-y-1">
            <li>• A new physical SIM card will be shipped to your registered address</li>
            <li>• Typical delivery time: 3-5 business days</li>
            <li>• You will receive an email with tracking information</li>
            <li>• The old SIM card will be deactivated once the new one is activated</li>
          </ul>
        </div>
      )}

      <div className="flex gap-3">
        <Button
          type="submit"
          disabled={loading || !simType || (simType === "esim" && !isValidEid)}
          loading={loading}
          loadingText="Processing…"
        >
          Submit Reissue Request
        </Button>
        <Button
          as="a"
          href={`/account/subscriptions/${subscriptionId}#sim-management`}
          variant="outline"
        >
          Cancel
        </Button>
      </div>
    </form>
  );
}

export function SimReissueContainer() {
  const params = useParams();
  const subscriptionId = params["id"] as string;
  const state = useSimReissueState(subscriptionId);

  return (
    <PageLayout
      icon={<DevicePhoneMobileIcon />}
      title="Reissue SIM"
      backLink={{ label: "Back to Subscription", href: `/account/subscriptions/${subscriptionId}` }}
    >
      <div className="max-w-3xl mx-auto">
        <div className="mb-4">
          <Link
            href={`/account/subscriptions/${subscriptionId}#sim-management`}
            className="text-primary hover:underline"
          >
            ← Back to SIM Management
          </Link>
        </div>
        <SubCard>
          <div className="mb-6">
            <h2 className="text-lg font-semibold text-foreground mb-2">Request SIM Reissue</h2>
            <p className="text-sm text-muted-foreground">
              If your SIM card is lost, damaged, or you need to switch between physical SIM and
              eSIM, you can request a replacement here.
            </p>
          </div>
          {state.message && (
            <div className="mb-4">
              <AlertBanner variant="success" title="Request Submitted">
                {state.message}
              </AlertBanner>
            </div>
          )}
          {state.error && (
            <div className="mb-4">
              <AlertBanner variant="error" title="Request Failed">
                {state.error}
              </AlertBanner>
            </div>
          )}
          {state.loadingDetails ? (
            <div className="animate-pulse space-y-4">
              <div className="h-32 bg-muted rounded-lg"></div>
              <div className="h-32 bg-muted rounded-lg"></div>
            </div>
          ) : (
            <ReissueForm state={state} subscriptionId={subscriptionId} />
          )}
        </SubCard>
      </div>
    </PageLayout>
  );
}

export default SimReissueContainer;
