"use client";

import React, { useState } from 'react';
import { 
  PlusIcon, 
  ArrowPathIcon, 
  XMarkIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon
} from '@heroicons/react/24/outline';
import { TopUpModal } from './TopUpModal';
import { authenticatedApi } from '@/lib/api';

interface SimActionsProps {
  subscriptionId: number;
  simType: 'physical' | 'esim';
  status: string;
  onTopUpSuccess?: () => void;
  onPlanChangeSuccess?: () => void;
  onCancelSuccess?: () => void;
  onReissueSuccess?: () => void;
}

export function SimActions({ 
  subscriptionId, 
  simType, 
  status,
  onTopUpSuccess,
  onPlanChangeSuccess,
  onCancelSuccess,
  onReissueSuccess
}: SimActionsProps) {
  const [showTopUpModal, setShowTopUpModal] = useState(false);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [showReissueConfirm, setShowReissueConfirm] = useState(false);
  const [loading, setLoading] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const isActive = status === 'active';
  const canTopUp = isActive;
  const canReissue = isActive && simType === 'esim';
  const canCancel = isActive;

  const handleReissueEsim = async () => {
    setLoading('reissue');
    setError(null);
    
    try {
      await authenticatedApi.post(`/subscriptions/${subscriptionId}/sim/reissue-esim`);
      
      setSuccess('eSIM profile reissued successfully');
      setShowReissueConfirm(false);
      onReissueSuccess?.();
    } catch (error: any) {
      setError(error instanceof Error ? error.message : 'Failed to reissue eSIM profile');
    } finally {
      setLoading(null);
    }
  };

  const handleCancelSim = async () => {
    setLoading('cancel');
    setError(null);
    
    try {
      await authenticatedApi.post(`/subscriptions/${subscriptionId}/sim/cancel`, {});
      
      setSuccess('SIM service cancelled successfully');
      setShowCancelConfirm(false);
      onCancelSuccess?.();
    } catch (error: any) {
      setError(error instanceof Error ? error.message : 'Failed to cancel SIM service');
    } finally {
      setLoading(null);
    }
  };

  // Clear success/error messages after 5 seconds
  React.useEffect(() => {
    if (success || error) {
      const timer = setTimeout(() => {
        setSuccess(null);
        setError(null);
      }, 5000);
      return () => clearTimeout(timer);
    }
  }, [success, error]);

  return (
    <div id="sim-actions" className="bg-white shadow rounded-lg">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-200">
        <h3 className="text-lg font-medium text-gray-900">SIM Management Actions</h3>
        <p className="text-sm text-gray-500 mt-1">Manage your SIM service</p>
      </div>

      {/* Content */}
      <div className="px-6 py-4">
        {/* Status Messages */}
        {success && (
          <div className="mb-4 bg-green-50 border border-green-200 rounded-lg p-4">
            <div className="flex items-center">
              <CheckCircleIcon className="h-5 w-5 text-green-500 mr-2" />
              <p className="text-sm text-green-800">{success}</p>
            </div>
          </div>
        )}

        {error && (
          <div className="mb-4 bg-red-50 border border-red-200 rounded-lg p-4">
            <div className="flex items-center">
              <ExclamationTriangleIcon className="h-5 w-5 text-red-500 mr-2" />
              <p className="text-sm text-red-800">{error}</p>
            </div>
          </div>
        )}

        {!isActive && (
          <div className="mb-4 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div className="flex items-center">
              <ExclamationTriangleIcon className="h-5 w-5 text-yellow-500 mr-2" />
              <p className="text-sm text-yellow-800">
                SIM management actions are only available for active services.
              </p>
            </div>
          </div>
        )}

        {/* Action Buttons */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Top Up Data */}
          <button
            onClick={() => setShowTopUpModal(true)}
            disabled={!canTopUp || loading !== null}
            className={`flex items-center justify-center px-4 py-3 border border-transparent rounded-lg text-sm font-medium transition-colors ${
              canTopUp && loading === null
                ? 'text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500'
                : 'text-gray-400 bg-gray-100 cursor-not-allowed'
            }`}
          >
            <PlusIcon className="h-4 w-4 mr-2" />
            {loading === 'topup' ? 'Processing...' : 'Top Up Data'}
          </button>

          {/* Reissue eSIM (only for eSIMs) */}
          {simType === 'esim' && (
            <button
              onClick={() => setShowReissueConfirm(true)}
              disabled={!canReissue || loading !== null}
              className={`flex items-center justify-center px-4 py-3 border border-transparent rounded-lg text-sm font-medium transition-colors ${
                canReissue && loading === null
                  ? 'text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500'
                  : 'text-gray-400 bg-gray-100 cursor-not-allowed'
              }`}
            >
              <ArrowPathIcon className="h-4 w-4 mr-2" />
              {loading === 'reissue' ? 'Processing...' : 'Reissue eSIM'}
            </button>
          )}

          {/* Cancel SIM */}
          <button
            onClick={() => setShowCancelConfirm(true)}
            disabled={!canCancel || loading !== null}
            className={`flex items-center justify-center px-4 py-3 border border-transparent rounded-lg text-sm font-medium transition-colors ${
              canCancel && loading === null
                ? 'text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500'
                : 'text-gray-400 bg-gray-100 cursor-not-allowed'
            }`}
          >
            <XMarkIcon className="h-4 w-4 mr-2" />
            {loading === 'cancel' ? 'Processing...' : 'Cancel SIM'}
          </button>
        </div>

        {/* Action Descriptions */}
        <div className="mt-6 space-y-3 text-sm text-gray-600">
          <div className="flex items-start">
            <PlusIcon className="h-4 w-4 text-blue-500 mr-2 mt-0.5 flex-shrink-0" />
            <div>
              <strong>Top Up Data:</strong> Add additional data quota to your SIM service. You can choose the amount and schedule it for later if needed.
            </div>
          </div>
          
          {simType === 'esim' && (
            <div className="flex items-start">
              <ArrowPathIcon className="h-4 w-4 text-green-500 mr-2 mt-0.5 flex-shrink-0" />
              <div>
                <strong>Reissue eSIM:</strong> Generate a new eSIM profile for download. Use this if your previous download failed or you need to install on a new device.
              </div>
            </div>
          )}
          
          <div className="flex items-start">
            <XMarkIcon className="h-4 w-4 text-red-500 mr-2 mt-0.5 flex-shrink-0" />
            <div>
              <strong>Cancel SIM:</strong> Permanently cancel your SIM service. This action cannot be undone and will terminate your service immediately.
            </div>
          </div>
        </div>
      </div>

      {/* Top Up Modal */}
      {showTopUpModal && (
        <TopUpModal
          subscriptionId={subscriptionId}
          onClose={() => setShowTopUpModal(false)}
          onSuccess={() => {
            setShowTopUpModal(false);
            setSuccess('Data top-up completed successfully');
            onTopUpSuccess?.();
          }}
          onError={(message) => setError(message)}
        />
      )}

      {/* Reissue eSIM Confirmation */}
      {showReissueConfirm && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
            <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
              <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div className="sm:flex sm:items-start">
                  <div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-green-100 sm:mx-0 sm:h-10 sm:w-10">
                    <ArrowPathIcon className="h-6 w-6 text-green-600" />
                  </div>
                  <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                    <h3 className="text-lg leading-6 font-medium text-gray-900">Reissue eSIM Profile</h3>
                    <div className="mt-2">
                      <p className="text-sm text-gray-500">
                        This will generate a new eSIM profile for download. Your current eSIM will remain active until you activate the new profile.
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button
                  type="button"
                  onClick={handleReissueEsim}
                  disabled={loading === 'reissue'}
                  className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50"
                >
                  {loading === 'reissue' ? 'Processing...' : 'Reissue eSIM'}
                </button>
                <button
                  type="button"
                  onClick={() => setShowReissueConfirm(false)}
                  disabled={loading === 'reissue'}
                  className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Cancel Confirmation */}
      {showCancelConfirm && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
            <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
              <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div className="sm:flex sm:items-start">
                  <div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                    <ExclamationTriangleIcon className="h-6 w-6 text-red-600" />
                  </div>
                  <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                    <h3 className="text-lg leading-6 font-medium text-gray-900">Cancel SIM Service</h3>
                    <div className="mt-2">
                      <p className="text-sm text-gray-500">
                        Are you sure you want to cancel this SIM service? This action cannot be undone and will permanently terminate your service.
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button
                  type="button"
                  onClick={handleCancelSim}
                  disabled={loading === 'cancel'}
                  className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50"
                >
                  {loading === 'cancel' ? 'Processing...' : 'Cancel SIM'}
                </button>
                <button
                  type="button"
                  onClick={() => setShowCancelConfirm(false)}
                  disabled={loading === 'cancel'}
                  className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
