"use client";

import React, { useEffect, useMemo, useState } from "react";
import { apiClient } from "@/core/api";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { Button } from "@/components/atoms/button";

interface SimFeatureTogglesProps {
  subscriptionId: number;
  voiceMailEnabled?: boolean;
  callWaitingEnabled?: boolean;
  internationalRoamingEnabled?: boolean;
  networkType?: string; // '4G' | '5G'
  onChanged?: () => void;
  embedded?: boolean; // when true, render without outer card wrappers
}

export function SimFeatureToggles({
  subscriptionId,
  voiceMailEnabled,
  callWaitingEnabled,
  internationalRoamingEnabled,
  networkType,
  onChanged,
  embedded = false,
}: SimFeatureTogglesProps) {
  // Initial values
  const initial = useMemo(
    () => ({
      vm: !!voiceMailEnabled,
      cw: !!callWaitingEnabled,
      ir: !!internationalRoamingEnabled,
      nt: networkType === "5G" ? "5G" : "4G",
    }),
    [voiceMailEnabled, callWaitingEnabled, internationalRoamingEnabled, networkType]
  );

  // Working values
  const [vm, setVm] = useState(initial.vm);
  const [cw, setCw] = useState(initial.cw);
  const [ir, setIr] = useState(initial.ir);
  const [nt, setNt] = useState<"4G" | "5G">(initial.nt as "4G" | "5G");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  useEffect(() => {
    setVm(initial.vm);
    setCw(initial.cw);
    setIr(initial.ir);
    setNt(initial.nt as "4G" | "5G");
  }, [initial.vm, initial.cw, initial.ir, initial.nt]);

  const reset = () => {
    setVm(initial.vm);
    setCw(initial.cw);
    setIr(initial.ir);
    setNt(initial.nt as "4G" | "5G");
    setError(null);
    setSuccess(null);
  };

  const applyChanges = async () => {
    setLoading(true);
    setError(null);
    setSuccess(null);
    try {
      const featurePayload: {
        voiceMailEnabled?: boolean;
        callWaitingEnabled?: boolean;
        internationalRoamingEnabled?: boolean;
        networkType?: "4G" | "5G";
      } = {};
      if (vm !== initial.vm) featurePayload.voiceMailEnabled = vm;
      if (cw !== initial.cw) featurePayload.callWaitingEnabled = cw;
      if (ir !== initial.ir) featurePayload.internationalRoamingEnabled = ir;
      if (nt !== initial.nt) featurePayload.networkType = nt;

      if (Object.keys(featurePayload).length > 0) {
        await apiClient.POST("/api/subscriptions/{id}/sim/features", {
          params: { path: { id: subscriptionId } },
          body: featurePayload,
        });
      }

      setSuccess("Changes submitted successfully");
      onChanged?.();
    } catch (e: unknown) {
      setError(
        process.env.NODE_ENV === "development"
          ? e instanceof Error
            ? e.message
            : "Failed to submit changes"
          : "Unable to submit changes right now. Please try again."
      );
    } finally {
      setLoading(false);
      setTimeout(() => setSuccess(null), 3000);
    }
  };

  return (
    <div className="space-y-6">
      {/* Service Options */}
      <div
        className={`${embedded ? "" : "bg-card rounded-xl border border-border shadow-[var(--cp-shadow-1)]"}`}
      >
        <div className={`${embedded ? "" : "p-6"} space-y-4`}>
          {/* Voice Mail */}
          <div className="flex items-center justify-between py-4">
            <div className="flex-1">
              <div className="text-sm font-medium text-foreground">Voice Mail</div>
              <div className="text-xs text-muted-foreground">¥300/month</div>
            </div>
            <button
              type="button"
              role="switch"
              aria-checked={vm}
              onClick={() => setVm(!vm)}
              className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-[var(--cp-duration-normal)] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background ${
                vm ? "bg-primary" : "bg-muted"
              }`}
            >
              <span
                className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-background shadow ring-0 transition duration-[var(--cp-duration-normal)] ease-in-out ${
                  vm ? "translate-x-5" : "translate-x-0"
                }`}
              />
            </button>
          </div>

          {/* Call Waiting */}
          <div className="flex items-center justify-between py-4">
            <div className="flex-1">
              <div className="text-sm font-medium text-foreground">Call Waiting</div>
              <div className="text-xs text-muted-foreground">¥300/month</div>
            </div>
            <button
              type="button"
              role="switch"
              aria-checked={cw}
              onClick={() => setCw(!cw)}
              className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-[var(--cp-duration-normal)] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background ${
                cw ? "bg-primary" : "bg-muted"
              }`}
            >
              <span
                className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-background shadow ring-0 transition duration-[var(--cp-duration-normal)] ease-in-out ${
                  cw ? "translate-x-5" : "translate-x-0"
                }`}
              />
            </button>
          </div>

          {/* International Roaming */}
          <div className="flex items-center justify-between py-4">
            <div className="flex-1">
              <div className="text-sm font-medium text-foreground">International Roaming</div>
              <div className="text-xs text-muted-foreground">Global connectivity</div>
            </div>
            <button
              type="button"
              role="switch"
              aria-checked={ir}
              onClick={() => setIr(!ir)}
              className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-[var(--cp-duration-normal)] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background ${
                ir ? "bg-primary" : "bg-muted"
              }`}
            >
              <span
                className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-background shadow ring-0 transition duration-[var(--cp-duration-normal)] ease-in-out ${
                  ir ? "translate-x-5" : "translate-x-0"
                }`}
              />
            </button>
          </div>

          <div className="border-t border-border pt-6">
            <div className="mb-4">
              <div className="text-sm font-medium text-foreground mb-1">Network Type</div>
              <div className="text-xs text-muted-foreground">
                Choose your preferred connectivity
              </div>
              <div className="text-xs text-danger mt-1">
                Voice, network, and plan changes must be requested at least 30 minutes apart. If you
                just changed another option, you may need to wait before submitting.
              </div>
            </div>
            <div className="flex gap-4">
              <div className="flex items-center space-x-2">
                <input
                  type="radio"
                  id="4g"
                  name="networkType"
                  value="4G"
                  checked={nt === "4G"}
                  onChange={() => setNt("4G")}
                  className="h-4 w-4 text-primary focus:ring-ring border-input"
                />
                <label htmlFor="4g" className="text-sm text-foreground/80">
                  4G
                </label>
              </div>
              <div className="flex items-center space-x-2">
                <input
                  type="radio"
                  id="5g"
                  name="networkType"
                  value="5G"
                  checked={nt === "5G"}
                  onChange={() => setNt("5G")}
                  className="h-4 w-4 text-primary focus:ring-ring border-input"
                />
                <label htmlFor="5g" className="text-sm text-foreground/80">
                  5G
                </label>
              </div>
            </div>
            <p className="text-xs text-muted-foreground mt-2">
              5G connectivity for enhanced speeds
            </p>
          </div>
        </div>
      </div>

      {/* Notes and Actions */}
      <div
        className={`${embedded ? "" : "bg-card rounded-xl border border-border p-6 shadow-[var(--cp-shadow-1)]"}`}
      >
        <AlertBanner variant="info" title="Important Notes" size="sm">
          <ul className="space-y-1 text-xs">
            <li>Changes take effect approximately 30 minutes after submission.</li>
            <li>You may need to restart your device after changes are applied.</li>
            <li>
              <span className="font-medium">
                Voice, network, and plan changes must be requested at least 30 minutes apart.
              </span>
            </li>
            <li>
              Voice Mail / Call Waiting changes must be requested before the 25th of the month.
            </li>
          </ul>
        </AlertBanner>

        {success && (
          <div className="mb-4">
            <AlertBanner variant="success" title="Success" size="sm" elevated>
              {success}
            </AlertBanner>
          </div>
        )}

        {error && (
          <div className="mb-4">
            <AlertBanner variant="error" title="Unable to apply changes" size="sm" elevated>
              {error}
            </AlertBanner>
          </div>
        )}

        <div className="flex flex-col sm:flex-row gap-3">
          <Button
            className="flex-1"
            onClick={() => void applyChanges()}
            loading={loading}
            loadingText="Applying…"
          >
            Apply Changes
          </Button>
          <Button
            className="flex-1 sm:flex-none"
            variant="outline"
            onClick={() => reset()}
            disabled={loading}
          >
            Reset
          </Button>
        </div>
      </div>
    </div>
  );
}
