import React, { useState, useEffect, useRef } from 'react';
import {
	ShoppingCartOutlined,
	SketchOutlined,
	CreditCardOutlined,
	DollarOutlined,
	ClusterOutlined,
	CheckCircleOutlined,
} from '@ant-design/icons';
import { Tabs, Alert, Tooltip, Badge } from 'antd';
import StripeSetting from './TabContent/StripeSetting';
import CheckoutSetting from './TabContent/CheckoutSetting';
import LocalPaymentMethods from './TabContent/LocalPaymentMethods';
import StripeSessions from './TabContent/StripeSessions';
import Features from './TabContent/Features';
import SetupHealth from '../../shared/SetupHealth';
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';

const NavTabs = () => {
	/**
	 * States
	 */
	const [ disabledTab, setDisabledTab ] = useState( false );
	const [ warning, setWarning ] = useState( false );
	const [ missingKeyWarning, setMissingKeyWarning ] = useState( false );
	const [ connectionWarning, setConnectionWarning ] = useState( false );
	const [ activeTab, setActiveTab ] = useState( () => {
		try {
			const savedTab = localStorage.getItem( 'activeTab' );
			return [ 'setup', '1', '2', '3', '4', '5' ].includes( savedTab ) ? savedTab : 'setup';
		} catch ( error ) { return 'setup'; }
	} );
	const [ stripeSettingSave, setStripeSettingSave ] = useState( '' );
	const tabContainer = useRef( null );
	const getTabStatus = () => {
		apiFetch( {
			path: '/sahcfwc/v1/stripe-check-data-exist/',
			method: 'Get',
		} )
			.then( ( response ) => {
				const hasStripeKey = response?.stripe_key === true;
				const countryMismatch =
					hasStripeKey &&
					response?.is_stripe_wc_country_match === false;

				setStripeSettingSave( hasStripeKey );
				setDisabledTab( countryMismatch );
				setWarning( countryMismatch );
				setMissingKeyWarning( response?.checkout_enabled === true && ! hasStripeKey );
				setConnectionWarning( response?.checkout_enabled === true && response?.stripe_connection_error === true );
			} )
			.catch( ( error ) => {
				console.error( 'Error fetching tab status:', error );
			} );
	};

	useEffect( () => {
		// The setup screen uses only its local health endpoint until a check is requested.
		if ( activeTab !== 'setup' ) { getTabStatus(); }
	}, [ activeTab ] );

	useEffect( () => {
		// Save active tab to local storage

		try { localStorage.setItem( 'activeTab', activeTab ); } catch ( error ) { /* Storage may be disabled. */ }
	}, [ activeTab ] );

	const navigateToTab = ( key ) => {
		setActiveTab( key );
		window.requestAnimationFrame( () => {
			tabContainer.current?.querySelector( '[role="tab"][aria-selected="true"]' )?.focus();
		} );
	};

	return (
		<>
			{ activeTab !== 'setup' && missingKeyWarning && (
				<Alert
					description={ __(
						'Stripe API key is required. Enter a key in Stripe Settings to enable checkout.',
						'sa-hosted-checkout-for-woocommerce'
					) }
					type="warning"
					showIcon={ true }
				/>
			) }
			{ activeTab !== 'setup' && connectionWarning && (
				<Alert
					description={ __(
						'Unable to verify the Stripe connection. Check the API key for the selected mode and try again.',
						'sa-hosted-checkout-for-woocommerce'
					) }
					type="warning"
					showIcon={ true }
				/>
			) }
			{ activeTab !== 'setup' && stripeSettingSave && warning && (
				<Alert
					description={ __(
						'The WooCommerce store country must match the country associated with your Stripe account.',
						'sa-hosted-checkout-for-woocommerce'
					) }
					type="error"
					showIcon={ true }
				/>
			) }
			<div ref={ tabContainer }><Tabs
				activeKey={ activeTab }
				onChange={ ( key ) => {
					setActiveTab( key );
				} }
				items={ [
					{
						key: 'setup',
						label: __( 'Setup & health', 'sa-hosted-checkout-for-woocommerce' ),
						icon: <CheckCircleOutlined />,
						children: <SetupHealth active={ activeTab === 'setup' } onNavigate={ navigateToTab } />,
					},
					{
						key: '1',
						label: __(
							'Stripe Settings',
							'sa-hosted-checkout-for-woocommerce'
						),
						icon: <CreditCardOutlined />,
						children: <StripeSetting />,
					},
					{
						key: '2',
						label: __(
							'Checkout Settings',
							'sa-hosted-checkout-for-woocommerce'
						),
						icon: <ShoppingCartOutlined />,
						children: <CheckoutSetting />,
					},
					{
						key: '3',
						label: __( 'Payment Methods', 'sa-hosted-checkout-for-woocommerce' ),
						icon: <DollarOutlined />,
						children: <LocalPaymentMethods />,
					},
					{
						key: '4',
						label: (
							<span className="disabled-prem">
								{ __(
									'Stripe Sessions',
									'sa-hosted-checkout-for-woocommerce'
								) }{ ' ' }
								<Tooltip title="Premium" placement="top">
									<i className="sahcfwc-info-icon">i</i>
								</Tooltip>
							</span>
						),
						icon: <ClusterOutlined className="disabled-prem" />,
						children: <StripeSessions />,
					},
					{
						key: '5',
						label: (
							<span className="glitter">
								{ __(
									'Features',
									'sa-hosted-checkout-for-woocommerce'
								) }{ ' ' }
							</span>
						),
						icon: <SketchOutlined className="glitter" />,
						children: <Features />,
						className: 'glitter',
					},
				] }
			/></div>
		</>
	);
};

export default NavTabs;
