"use client";

import React, { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import {
  DevicePhoneMobileIcon,
  ExclamationTriangleIcon,
  ArrowPathIcon,
  SignalIcon,
  ArrowsRightLeftIcon,
  ArrowPathRoundedSquareIcon,
  XCircleIcon,
} from "@heroicons/react/24/outline";
import { apiClient } from "@/lib/api";
import { useSubscription, useSubscriptionInvoices } from "@/features/subscriptions/hooks";
import { useCreateInvoiceSsoLink } from "@/features/billing/hooks/useBilling";
import { format } from "date-fns";
import { Formatting } from "@customer-portal/domain/toolkit";

const { formatCurrency } = Formatting;

interface SimManagementSectionProps {
  subscriptionId: number;
}

interface SimDetails {
  account: string;
  msisdn: string;
  iccid?: string;
  imsi?: string;
  eid?: string;
  planCode: string;
  status: "active" | "suspended" | "cancelled" | "pending";
  simType: "physical" | "esim" | "standard" | "nano" | "micro";
  remainingQuotaMb: number;
  remainingQuotaKb: number;
  voiceMailEnabled?: boolean;
  callWaitingEnabled?: boolean;
  internationalRoamingEnabled?: boolean;
  networkType?: string;
}

interface SimInfo {
  details: SimDetails;
  usage?: {
    todayUsageMb: number;
    monthlyUsageMb?: number;
    recentDaysUsage?: Array<{ date: string; usageMb: number }>;
  };
}

export function SimManagementSection({ subscriptionId }: SimManagementSectionProps) {
  const router = useRouter();
  const [simInfo, setSimInfo] = useState<SimInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Navigation handlers
  const navigateToTopUp = () => router.push(`/subscriptions/${subscriptionId}/sim/top-up`);
  const navigateToChangePlan = () => router.push(`/subscriptions/${subscriptionId}/sim/change-plan`);
  const navigateToReissue = () => router.push(`/subscriptions/${subscriptionId}/sim/reissue`);
  const navigateToCancel = () => router.push(`/subscriptions/${subscriptionId}/sim/cancel`);

  // Fetch subscription data
  const { data: subscription } = useSubscription(subscriptionId);
  
  // Fetch latest invoice (limit 1)
  const { data: invoicesData } = useSubscriptionInvoices(subscriptionId, { limit: 1 });
  const latestInvoice = invoicesData?.invoices?.[0];

  // SSO link mutation for payment
  const createSsoLink = useCreateInvoiceSsoLink({
    onSuccess: (data) => {
      if (data.url) {
        window.open(data.url, '_blank');
      }
    },
  });

  const fetchSimInfo = useCallback(async () => {
    try {
      setError(null);

      const response = await apiClient.GET("/api/subscriptions/{id}/sim", {
        params: { path: { id: subscriptionId } },
      });

      const payload = response.data as { details: SimDetails; usage: any } | undefined;

      if (!payload) {
        throw new Error("Failed to load SIM information");
      }

      setSimInfo({ 
        details: payload.details,
        usage: payload.usage 
      });
    } catch (err: unknown) {
      const hasStatus = (v: unknown): v is { status: number } =>
        typeof v === "object" &&
        v !== null &&
        "status" in v &&
        typeof (v as { status: unknown }).status === "number";
      if (hasStatus(err) && err.status === 400) {
        setError("This subscription is not a SIM service");
      } else {
        setError(err instanceof Error ? err.message : "Failed to load SIM information");
      }
    } finally {
      setLoading(false);
    }
  }, [subscriptionId]);

  useEffect(() => {
    void fetchSimInfo();
  }, [fetchSimInfo]);

  const handleRefresh = () => {
    setLoading(true);
    void fetchSimInfo();
  };

  const handleActionSuccess = () => {
    void fetchSimInfo();
  };

  const handlePayInvoice = () => {
    if (latestInvoice?.id) {
      createSsoLink.mutate({ invoiceId: latestInvoice.id, target: 'pay' });
    }
  };

  const formatDate = (dateString: string | undefined) => {
    if (!dateString) return "N/A";
    try {
      return format(new Date(dateString), "MMM d yyyy");
    } catch {
      return "Invalid date";
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="bg-white/90 backdrop-blur-sm shadow-sm rounded-lg border border-gray-200 p-8">
          <div className="animate-pulse space-y-6">
            <div className="h-6 bg-gradient-to-r from-gray-200 to-gray-300 rounded-lg w-3/4"></div>
            <div className="h-48 bg-gradient-to-r from-gray-200 to-gray-300 rounded-xl"></div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white/90 backdrop-blur-sm shadow-sm rounded-lg border border-red-200 p-8">
        <div className="text-center py-12">
          <div className="bg-red-50 rounded-full p-4 w-20 h-20 mx-auto mb-6">
            <ExclamationTriangleIcon className="h-12 w-12 text-red-500 mx-auto" />
          </div>
          <h3 className="text-xl font-semibold text-gray-900 mb-3">
            Unable to Load SIM Information
          </h3>
          <p className="text-gray-600 mb-8 max-w-md mx-auto">{error}</p>
          <button
            onClick={handleRefresh}
            className="inline-flex items-center px-6 py-3 border border-transparent text-sm font-semibold rounded-xl text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200"
          >
            <ArrowPathIcon className="h-5 w-5 mr-2" />
            Retry
          </button>
        </div>
      </div>
    );
  }

  if (!simInfo) {
    return null;
  }

  const remainingGB = (simInfo.details.remainingQuotaMb / 1000).toFixed(1);
  const usedGB = simInfo.usage?.monthlyUsageMb 
    ? (simInfo.usage.monthlyUsageMb / 1000).toFixed(2)
    : simInfo.usage?.todayUsageMb 
    ? (simInfo.usage.todayUsageMb / 1000).toFixed(2)
    : "0.00";

  // Calculate percentage for circle
  const totalGB = parseFloat(remainingGB) + parseFloat(usedGB);
  const usagePercentage = totalGB > 0 ? (parseFloat(usedGB) / totalGB) * 100 : 0;
  const circumference = 2 * Math.PI * 88;
  const strokeDashoffset = circumference - (usagePercentage / 100) * circumference;

  return (
    <div id="sim-management" className="space-y-6">
      {/* Main Content Card */}
      <div className="bg-white/90 backdrop-blur-sm shadow-sm rounded-lg border border-gray-200 p-6">
        {/* Top Section with Details and Data Circle */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
          {/* Left: Subscription Details */}
          <div className="space-y-4">
            <div>
              <p className="text-sm text-gray-600">
                Monthly Cost: <span className="font-semibold text-gray-900">
                  {subscription ? formatCurrency(subscription.amount) : "Loading..."}
                </span>
              </p>
            </div>
            <div>
              <p className="text-sm text-gray-600">
                Next Billing: <span className="font-semibold text-gray-900">
                  {subscription?.nextDue ? formatDate(subscription.nextDue) : "N/A"}
                </span>
              </p>
            </div>
            <div>
              <p className="text-sm text-gray-600">
                Registered: <span className="font-semibold text-gray-900">
                  {subscription?.registrationDate ? formatDate(subscription.registrationDate) : "N/A"}
                </span>
              </p>
            </div>
            
            {/* Latest Invoice Section - Mobile View */}
            {latestInvoice && (
              <div className="lg:hidden mt-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
                <p className="text-xs text-gray-600 mb-1">Latest Invoice</p>
                <p className="text-2xl font-bold text-gray-900 mb-3">
                  {formatCurrency(latestInvoice.total)}
                </p>
                <button
                  onClick={handlePayInvoice}
                  disabled={createSsoLink.isPending || latestInvoice.status === 'paid'}
                  className="w-full px-4 py-2 bg-blue-600 text-white text-sm font-semibold rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
                >
                  {latestInvoice.status === 'paid' ? 'PAID' : createSsoLink.isPending ? 'Loading...' : 'PAY'}
                </button>
              </div>
            )}
            
            {/* Top Up Data Button */}
            <div className="pt-4">
              <button
                onClick={navigateToTopUp}
                className="w-full px-6 py-3 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-colors"
              >
                Top Up Data
              </button>
            </div>
          </div>

          {/* Right: Data Usage Circle */}
          <div className="flex items-center justify-center">
            <div className="relative w-48 h-48">
              <svg className="w-full h-full transform -rotate-90">
                <circle
                  cx="96"
                  cy="96"
                  r="88"
                  fill="none"
                  stroke="#e5e7eb"
                  strokeWidth="12"
                />
                <circle
                  cx="96"
                  cy="96"
                  r="88"
                  fill="none"
                  stroke="#3b82f6"
                  strokeWidth="12"
                  strokeLinecap="round"
                  strokeDasharray={circumference}
                  strokeDashoffset={strokeDashoffset}
                  className="transition-all duration-500"
                />
              </svg>
              <div className="absolute inset-0 flex flex-col items-center justify-center">
                <p className="text-xs text-gray-600">Remaining data</p>
                <p className="text-4xl font-bold text-gray-900">{remainingGB} GB</p>
                <p className="text-sm text-blue-600">-{usedGB} GB</p>
              </div>
            </div>
          </div>
        </div>

        {/* SIM Management Actions - 2x2 Grid on Desktop, 2x2 on Mobile */}
        <div className="mb-8">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">SIM Management Actions</h3>
          <div className="grid grid-cols-2 gap-4">
            <button
              onClick={navigateToTopUp}
              className="flex flex-col items-center justify-center p-6 bg-white border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:shadow-md transition-all duration-200"
            >
              <SignalIcon className="h-8 w-8 text-gray-700 mb-2" />
              <span className="text-sm font-medium text-gray-900">Data Top up</span>
            </button>
            
            <button
              onClick={navigateToChangePlan}
              className="flex flex-col items-center justify-center p-6 bg-white border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:shadow-md transition-all duration-200"
            >
              <ArrowsRightLeftIcon className="h-8 w-8 text-gray-700 mb-2" />
              <span className="text-sm font-medium text-gray-900">Change Plan</span>
            </button>
            
            <button
              onClick={navigateToReissue}
              className="flex flex-col items-center justify-center p-6 bg-white border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:shadow-md transition-all duration-200"
            >
              <ArrowPathRoundedSquareIcon className="h-8 w-8 text-gray-700 mb-2" />
              <span className="text-sm font-medium text-gray-900">Reissue SIM</span>
            </button>
            
            <button
              onClick={navigateToCancel}
              className="flex flex-col items-center justify-center p-6 bg-white border-2 border-gray-200 rounded-lg hover:border-red-500 hover:shadow-md transition-all duration-200"
            >
              <XCircleIcon className="h-8 w-8 text-gray-700 mb-2" />
              <span className="text-sm font-medium text-gray-900">Cancel SIM</span>
            </button>
          </div>
        </div>

        {/* Voice Status Section */}
        <div className="mb-8">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Voice Status</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="p-4 bg-white border border-gray-200 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium text-gray-900">Voice Mail</p>
                  {simInfo.details.voiceMailEnabled && (
                    <p className="text-xs text-blue-600">
                      On
                      <br />
                      <span className="text-blue-600">Enabled</span>
                    </p>
                  )}
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={simInfo.details.voiceMailEnabled || false}
                    className="sr-only peer"
                    readOnly
                  />
                  <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                </label>
              </div>
            </div>

            <div className="p-4 bg-white border border-gray-200 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium text-gray-900">Network Type</p>
                  <p className="text-xs text-gray-600">
                    {simInfo.details.networkType ? simInfo.details.networkType : 'Disabled'}
                  </p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={!!simInfo.details.networkType}
                    className="sr-only peer"
                    readOnly
                  />
                  <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                </label>
              </div>
            </div>

            <div className="p-4 bg-white border border-gray-200 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium text-gray-900">Call Waiting</p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={simInfo.details.callWaitingEnabled || false}
                    className="sr-only peer"
                    readOnly
                  />
                  <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                </label>
              </div>
            </div>

            <div className="p-4 bg-white border border-gray-200 rounded-lg">
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium text-gray-900">International Roaming</p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={simInfo.details.internationalRoamingEnabled || false}
                    className="sr-only peer"
                    readOnly
                  />
                  <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                </label>
              </div>
            </div>
          </div>
        </div>

        {/* Important Notes */}
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-3">Important Notes</h3>
          <ul className="space-y-2 text-sm text-gray-700">
            <li className="flex items-start">
              <span className="mr-2">•</span>
              <span>Changes will take effect instantaneously (approx. 30min)</span>
            </li>
            <li className="flex items-start">
              <span className="mr-2">•</span>
              <span>May require smartphone device restart after changes are applied</span>
            </li>
            <li className="flex items-start">
              <span className="mr-2">•</span>
              <span>Voice, network, and plan changes must be requested at least 30 minutes apart.</span>
            </li>
            <li className="flex items-start">
              <span className="mr-2">•</span>
              <span>Changes to Voice Mail / Call Waiting must be requested before the 25th of the month</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
}
