'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslations, useLocale } from 'next-intl';
import {
  getSubscriptionOverview,
  getAllPlans,
  createCheckoutSession,
  createPortalSession,
  syncSubscriptionFromStripe,
  formatPrice,
  getPlanBadgeColor,
  getStatusBadgeColor,
  type SubscriptionPlan,
  type BillingInterval,
} from '@/lib/api/subscriptions';

export default function SubscriptionTab() {
  const t = useTranslations('dashboard.subscription');
  const locale = useLocale();
  const searchParams = useSearchParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const [billingInterval, setBillingInterval] = useState<BillingInterval>('monthly');
  const [selectedPlan, setSelectedPlan] = useState<SubscriptionPlan | null>(null);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [isRefreshing, setIsRefreshing] = useState(false);

  const {
    data: subscription,
    isLoading: loadingSubscription,
    refetch: refetchSubscription,
  } = useQuery({
    queryKey: ['subscription'],
    queryFn: getSubscriptionOverview,
    refetchInterval: isRefreshing ? 2000 : false,
  });

  const { data: plansData, isLoading: loadingPlans } = useQuery({
    queryKey: ['plans'],
    queryFn: getAllPlans,
  });

  const handleStripeRedirect = useCallback(async () => {
    const isSuccess = searchParams.get('success') === 'true';
    const isCanceled = searchParams.get('canceled') === 'true';
    const sessionId = searchParams.get('session_id') || undefined;

    if (isSuccess) {
      setSuccess(t('successMessage'));
      setIsRefreshing(true);

      try {
        console.log('Syncing subscription with sessionId:', sessionId);
        await syncSubscriptionFromStripe(sessionId);
        await queryClient.invalidateQueries({ queryKey: ['subscription'] });
        await queryClient.invalidateQueries({ queryKey: ['canInvite'] });
        await refetchSubscription();
        await new Promise(resolve => setTimeout(resolve, 1500));
        await syncSubscriptionFromStripe(sessionId);
        await queryClient.invalidateQueries({ queryKey: ['subscription'] });
        await refetchSubscription();
      } catch (err) {
        console.error('Error syncing subscription:', err);
        await refetchSubscription();
      }

      setIsRefreshing(false);
      router.replace('/dashboard/settings/organization', { scroll: false });
      setTimeout(() => setSuccess(''), 5000);
    } else if (isCanceled) {
      setError(t('canceledMessage'));
      router.replace('/dashboard/settings/organization', { scroll: false });
      setTimeout(() => setError(''), 5000);
    }
  }, [searchParams, queryClient, refetchSubscription, router, t]);

  useEffect(() => {
    handleStripeRedirect();
  }, [handleStripeRedirect]);

  const checkoutMutation = useMutation({
    mutationFn: (plan: SubscriptionPlan) => createCheckoutSession({ plan, billingInterval }),
    onSuccess: data => {
      window.location.href = data.sessionUrl;
    },
    onError: (err: Error) => {
      setError(err.message || t('checkoutError'));
      setTimeout(() => setError(''), 5000);
    },
  });

  const portalMutation = useMutation({
    mutationFn: () => createPortalSession(),
    onSuccess: data => {
      window.location.href = data.sessionUrl;
    },
    onError: (err: Error) => {
      setError(err.message || t('portalError'));
      setTimeout(() => setError(''), 5000);
    },
  });

  const handleUpgrade = (plan: SubscriptionPlan) => {
    if (plan === 'BRONZE') return;
    setSelectedPlan(plan);
    checkoutMutation.mutate(plan);
  };

  const handleManageBilling = () => {
    portalMutation.mutate();
  };

  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      await syncSubscriptionFromStripe();
      await queryClient.invalidateQueries({ queryKey: ['subscription'] });
      await queryClient.invalidateQueries({ queryKey: ['canInvite'] });
      await refetchSubscription();
    } catch (err) {
      console.error('Error syncing subscription:', err);
      await refetchSubscription();
    }
    setIsRefreshing(false);
  };

  const isCurrentPlan = (plan: SubscriptionPlan): boolean => {
    return subscription?.plan === plan;
  };

  const canUpgrade = (plan: SubscriptionPlan): boolean => {
    if (!subscription) return false;
    const planOrder: SubscriptionPlan[] = ['BRONZE', 'SILVER', 'GOLD', 'PLATINIUM'];
    return planOrder.indexOf(plan) > planOrder.indexOf(subscription.plan);
  };

  const isLoading = loadingSubscription || loadingPlans;

  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          <div className="h-32 bg-gray-200 rounded"></div>
          <div className="h-64 bg-gray-200 rounded"></div>
        </div>
      </div>
    );
  }

  const usagePercentage = subscription
    ? subscription.maxLicenses === -1
      ? 0
      : (subscription.usedLicenses / subscription.maxLicenses) * 100
    : 0;

  return (
    <div className="space-y-6">
      {/* Alerts */}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          {error}
        </div>
      )}
      {success && (
        <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg flex items-center justify-between">
          <span>{success}</span>
          {isRefreshing && (
            <span className="text-sm text-green-600 flex items-center gap-2">
              <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                  fill="none"
                />
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                />
              </svg>
              {t('updatingMessage')}
            </span>
          )}
        </div>
      )}

      {/* Current Plan */}
      {subscription && (
        <div className="bg-gray-50 rounded-lg p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-medium text-gray-900">{t('currentPlan')}</h3>
            <button
              onClick={handleRefresh}
              disabled={isRefreshing}
              className="text-sm text-blue-600 hover:text-blue-800 disabled:opacity-50 flex items-center gap-1"
            >
              <svg
                className={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`}
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                />
              </svg>
              {isRefreshing ? t('refreshing') : t('refresh')}
            </button>
          </div>
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="flex flex-wrap items-center gap-3">
              <span
                className={`px-3 py-1 rounded-full text-sm font-medium ${getPlanBadgeColor(subscription.plan)}`}
              >
                {subscription.planDetails.name}
              </span>
              <span
                className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusBadgeColor(subscription.status)}`}
              >
                {subscription.status === 'ACTIVE' ? t('statusActive') : subscription.status}
              </span>
              {subscription.cancelAtPeriodEnd && (
                <span className="px-3 py-1 rounded-full text-sm font-medium bg-orange-100 text-orange-800">
                  {t('cancelAtPeriodEnd')}
                </span>
              )}
            </div>
            {subscription.plan !== 'BRONZE' && (
              <button
                onClick={handleManageBilling}
                disabled={portalMutation.isPending}
                className="px-4 py-2 text-sm font-medium text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded-lg disabled:opacity-50 transition-colors"
              >
                {portalMutation.isPending ? t('manageBillingLoading') : t('manageBilling')}
              </button>
            )}
          </div>

          {/* License Usage */}
          <div className="mt-6">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium text-gray-700">{t('licenseUsage')}</span>
              <span className="text-sm text-gray-500">
                {subscription.usedLicenses} /{' '}
                {subscription.maxLicenses === -1 ? t('unlimited') : subscription.maxLicenses}
              </span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2.5">
              <div
                className={`h-2.5 rounded-full ${
                  usagePercentage >= 90
                    ? 'bg-red-600'
                    : usagePercentage >= 70
                      ? 'bg-yellow-500'
                      : 'bg-blue-600'
                }`}
                style={{
                  width:
                    subscription.maxLicenses === -1 ? '10%' : `${Math.min(usagePercentage, 100)}%`,
                }}
              ></div>
            </div>
            {subscription.availableLicenses !== -1 && subscription.availableLicenses <= 2 && (
              <p className="mt-2 text-sm text-amber-600">
                {subscription.availableLicenses === 0
                  ? t('noLicenses')
                  : t('licensesRemaining', { count: subscription.availableLicenses })}
              </p>
            )}
          </div>

          {/* Billing Period */}
          {subscription.currentPeriodEnd && (
            <div className="mt-4 text-sm text-gray-500">
              {t('currentPeriod')}{' '}
              {new Date(subscription.currentPeriodEnd).toLocaleDateString(locale, {
                day: 'numeric',
                month: 'long',
                year: 'numeric',
              })}
            </div>
          )}
        </div>
      )}

      {/* Plans Grid */}
      <div className="space-y-4">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <h3 className="text-lg font-medium text-gray-900">{t('availablePlans')}</h3>
          <div className="flex items-center gap-2 bg-gray-100 p-1 rounded-lg">
            <button
              onClick={() => setBillingInterval('monthly')}
              className={`px-4 py-2 text-sm font-medium rounded-md transition ${
                billingInterval === 'monthly'
                  ? 'bg-white shadow text-gray-900'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              {t('billingMonthly')}
            </button>
            <button
              onClick={() => setBillingInterval('yearly')}
              className={`px-4 py-2 text-sm font-medium rounded-md transition ${
                billingInterval === 'yearly'
                  ? 'bg-white shadow text-gray-900'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              {t('billingYearly')}
              <span className="ml-1 text-xs text-green-600">{t('yearlySaving')}</span>
            </button>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {plansData?.plans.map(plan => (
            <div
              key={plan.plan}
              className={`bg-white rounded-lg border-2 p-5 ${
                isCurrentPlan(plan.plan)
                  ? 'border-blue-500 shadow-md'
                  : 'border-gray-200 hover:border-gray-300 hover:shadow transition'
              }`}
            >
              <div className="text-center">
                <h4 className="text-lg font-semibold text-gray-900">{plan.name}</h4>
                <div className="mt-3">
                  <span className="text-2xl font-bold text-gray-900">
                    {plan.plan === 'PLATINIUM'
                      ? t('customQuote')
                      : formatPrice(
                          billingInterval === 'yearly' ? plan.yearlyPriceEur : plan.monthlyPriceEur
                        )}
                  </span>
                  {plan.plan !== 'PLATINIUM' && plan.plan !== 'BRONZE' && (
                    <span className="text-gray-500 text-sm">
                      {billingInterval === 'yearly' ? t('perYear') : t('perMonth')}
                    </span>
                  )}
                </div>
                <p className="mt-2 text-sm text-gray-500">
                  {plan.maxLicenses === -1
                    ? t('unlimitedUsers')
                    : t('maxUsers', { count: plan.maxLicenses })}
                </p>
              </div>

              <ul className="mt-4 space-y-2">
                {plan.features.slice(0, 4).map((feature, index) => (
                  <li key={index} className="flex items-start gap-2">
                    <svg
                      className="h-5 w-5 text-green-500 flex-shrink-0 mt-0.5"
                      fill="currentColor"
                      viewBox="0 0 20 20"
                    >
                      <path
                        fillRule="evenodd"
                        d="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"
                        clipRule="evenodd"
                      />
                    </svg>
                    <span className="text-sm text-gray-600">{feature}</span>
                  </li>
                ))}
              </ul>

              <div className="mt-5">
                {isCurrentPlan(plan.plan) ? (
                  <button
                    disabled
                    className="w-full px-4 py-2 text-sm font-medium text-gray-500 bg-gray-100 rounded-lg cursor-not-allowed"
                  >
                    {t('currentPlanButton')}
                  </button>
                ) : plan.plan === 'PLATINIUM' ? (
                  <a
                    href="mailto:sales@xpeditis.com?subject=Demande Enterprise"
                    className="block w-full px-4 py-2 text-sm font-medium text-center text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition"
                  >
                    {t('contactUs')}
                  </a>
                ) : canUpgrade(plan.plan) ? (
                  <button
                    onClick={() => handleUpgrade(plan.plan)}
                    disabled={checkoutMutation.isPending && selectedPlan === plan.plan}
                    className="w-full px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition disabled:opacity-50"
                  >
                    {checkoutMutation.isPending && selectedPlan === plan.plan
                      ? t('upgradeLoading')
                      : t('upgradeButton')}
                  </button>
                ) : (
                  <button
                    disabled
                    className="w-full px-4 py-2 text-sm font-medium text-gray-400 bg-gray-100 rounded-lg cursor-not-allowed"
                  >
                    {t('downgrade')}
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
