import { useState } from "react";
import { SidebarProvider } from "@/components/ui/sidebar";
import { AppSidebar } from "@/components/AppSidebar";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useTranslation } from 'react-i18next';
import { useShop } from "@/components/context/ShopContext";
import { useSubscription, useUpdateSubscription } from "@/hooks/useSubscription";
import { usePlans } from "@/hooks/usePlans";
import {
  Zap,
  Star,
  TrendingUp,
  Crown,
  Check,
  AlertCircle,
  Loader2,
  Info
} from "lucide-react";
import {
  getPlanPrice,
  formatCurrency,
  type Currency,
  type PlanWithTranslation
} from "@/types/subscription.types";

// Icon mapping for plans
const planIcons: Record<string, React.ElementType> = {
  'Zap': Zap,
  'Star': Star,
  'TrendingUp': TrendingUp,
  'Crown': Crown
};

export default function BillingPlans() {
  const { t } = useTranslation();
  const { selectedShop } = useShop();
  const [selectedPlanId, setSelectedPlanId] = useState<string | null>(null);
  const [isChangingPlan, setIsChangingPlan] = useState(false);

  // Hooks
  const {
    subscription,
    isLoading: subLoading,
    refetch: refetchSubscription
  } = useSubscription(selectedShop?.id);

  const { plans, isLoading: plansLoading } = usePlans();
  const { changePlan, isUpdating } = useUpdateSubscription();

  const currentCurrency: Currency = (subscription?.currency as Currency) || 'HUF';
  const isLoading = subLoading || plansLoading;

  // Handle plan selection
  const handleSelectPlan = async (plan: PlanWithTranslation) => {
    if (!selectedShop?.id || isUpdating) return;

    // Don't allow selecting trial if already used
    if (plan.is_trial && subscription && subscription.status !== 'trial') {
      return;
    }

    // Don't allow selecting current plan
    if (subscription?.plan_id === plan.id) {
      return;
    }

    setSelectedPlanId(plan.id);
    setIsChangingPlan(true);

    const success = await changePlan(selectedShop.id, plan.id, plan);
    if (success) {
      await refetchSubscription();
    }

    setIsChangingPlan(false);
    setSelectedPlanId(null);
  };

  // Render loading state
  if (isLoading) {
    return (
      <SidebarProvider>
        <div className="min-h-screen flex w-full bg-slate-900">
          <AppSidebar />
          <main className="flex-1 bg-slate-900 text-white flex items-center justify-center">
            <Loader2 className="w-8 h-8 animate-spin text-cyan-500" />
          </main>
        </div>
      </SidebarProvider>
    );
  }

  // No shop selected
  if (!selectedShop) {
    return (
      <SidebarProvider>
        <div className="min-h-screen flex w-full bg-slate-900">
          <AppSidebar />
          <main className="flex-1 bg-slate-900 text-white p-6">
            <div className="text-center py-20">
              <AlertCircle className="w-16 h-16 text-yellow-500 mx-auto mb-4" />
              <h2 className="text-2xl font-bold mb-2">{t('billing.noShopSelected')}</h2>
              <p className="text-slate-400">{t('billing.selectShopFirst')}</p>
            </div>
          </main>
        </div>
      </SidebarProvider>
    );
  }

  return (
    <SidebarProvider>
      <div className="min-h-screen flex w-full bg-slate-900">
        <AppSidebar />
        <main className="flex-1 bg-slate-900 text-white">
          <div className="flex flex-col gap-6 p-6">
            {/* Header */}
            <div>
              <h1 className="text-3xl font-bold text-white">{t('billing.chooseYourPlan')}</h1>
              <p className="text-slate-400 mt-2">
                {t('billing.subtitle')}
              </p>
            </div>

            {/* Plan Cards Grid */}
            <div className="space-y-6">
              {/* Free Trial Card - Separate */}
              {plans.filter(p => p.is_trial).map(plan => {
                const Icon = planIcons[plan.icon_name || 'Zap'] || Zap;
                const isCurrentPlan = subscription?.plan_id === plan.id;
                const isDisabled = subscription && subscription.status !== 'trial';

                return (
                  <Card
                    key={plan.id}
                    className={`relative border-2 border-dashed transition-all cursor-pointer ${
                      isCurrentPlan
                        ? 'border-cyan-500 bg-slate-800/80'
                        : isDisabled
                        ? 'border-slate-700 bg-slate-800/30 opacity-50 cursor-not-allowed'
                        : 'border-slate-600 bg-slate-800/50 hover:border-cyan-500/50'
                    }`}
                    onClick={() => !isDisabled && handleSelectPlan(plan)}
                  >
                    <CardContent className="p-6">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-4">
                          <div className="w-12 h-12 rounded-lg bg-slate-700/50 flex items-center justify-center">
                            <Icon className="w-6 h-6 text-yellow-400" />
                          </div>
                          <div>
                            <div className="flex items-center gap-2">
                              <Zap className="w-4 h-4 text-yellow-400" />
                              <span className="font-semibold text-white">
                                {plan.translations.name}
                              </span>
                            </div>
                            <p className="text-sm text-slate-400 mt-1">
                              {plan.translations.description}
                            </p>
                          </div>
                        </div>
                        <div className="flex items-center gap-4">
                          <div className="text-right">
                            <div className="text-2xl font-bold text-white">
                              {formatCurrency(getPlanPrice(plan, currentCurrency), currentCurrency)}
                            </div>
                            <div className="text-sm text-slate-400">
                              {plan.translations.period_label}
                            </div>
                          </div>
                          <div className={`w-6 h-6 rounded-full border-2 flex items-center justify-center ${
                            isCurrentPlan ? 'border-cyan-500 bg-cyan-500' : 'border-slate-600'
                          }`}>
                            {isCurrentPlan && <Check className="w-4 h-4 text-white" />}
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}

              {/* Paid Plans Grid */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {plans.filter(p => !p.is_trial).map(plan => {
                  const Icon = planIcons[plan.icon_name || 'Star'] || Star;
                  const isCurrentPlan = subscription?.plan_id === plan.id;
                  const isSelected = selectedPlanId === plan.id;

                  return (
                    <Card
                      key={plan.id}
                      className={`relative transition-all cursor-pointer ${
                        plan.is_popular
                          ? 'border-2 border-cyan-500 bg-slate-800'
                          : isCurrentPlan
                          ? 'border-2 border-cyan-500/50 bg-slate-800'
                          : 'border border-slate-700 bg-slate-800/50 hover:border-slate-600'
                      }`}
                      onClick={() => handleSelectPlan(plan)}
                    >
                      {/* Most Popular Badge */}
                      {plan.translations.badge_text && (
                        <div className="absolute -top-3 left-1/2 transform -translate-x-1/2 z-10">
                          <Badge className="bg-cyan-500 text-white px-3 py-1 text-xs font-semibold">
                            <Star className="w-3 h-3 mr-1 inline" />
                            {plan.translations.badge_text}
                          </Badge>
                        </div>
                      )}

                      <CardHeader className="pt-6 pb-2">
                        <CardTitle className="text-lg text-white font-semibold">
                          {plan.translations.name}
                        </CardTitle>
                        <p className="text-sm text-slate-400">
                          {plan.translations.description}
                        </p>
                      </CardHeader>

                      <CardContent className="space-y-4">
                        {/* Price */}
                        <div className="flex items-baseline gap-1">
                          <span className="text-3xl font-bold text-white">
                            {formatCurrency(getPlanPrice(plan, currentCurrency), currentCurrency).replace(/[^\d,.\s]/g, '')}
                          </span>
                          <span className="text-lg text-slate-400">
                            {currentCurrency === 'HUF' ? ' Ft' : currentCurrency === 'EUR' ? '€' : '$'}
                          </span>
                          <span className="text-slate-400">{plan.translations.period_label}</span>
                        </div>

                        <p className="text-xs text-slate-500">+ {t('billing.vat')}</p>

                        {/* Features List */}
                        <div className="space-y-3 pt-2">
                          {plan.features.map((feature) => (
                            <div key={feature.id} className="flex items-start gap-2">
                              <Check className={`w-4 h-4 mt-0.5 flex-shrink-0 ${
                                feature.is_highlighted ? 'text-cyan-400' : 'text-green-500'
                              }`} />
                              <span className={`text-sm ${
                                feature.is_highlighted
                                  ? 'text-white font-medium'
                                  : 'text-slate-300'
                              }`}>
                                {feature.translations.label}
                              </span>
                            </div>
                          ))}
                        </div>

                        {/* Overage Rate */}
                        {plan.translations.overage_label && (
                          <div className="pt-4 border-t border-slate-700">
                            <p className="text-sm text-slate-400">
                              {plan.translations.overage_label}
                            </p>
                          </div>
                        )}

                        {/* Select Button */}
                        <Button
                          className={`w-full mt-4 ${
                            isCurrentPlan
                              ? 'bg-slate-700 text-slate-300 cursor-default'
                              : plan.is_popular
                              ? 'bg-cyan-500 hover:bg-cyan-600 text-white'
                              : 'bg-slate-700 hover:bg-slate-600 text-white'
                          }`}
                          disabled={isCurrentPlan || isChangingPlan}
                        >
                          {isSelected && isChangingPlan ? (
                            <Loader2 className="w-4 h-4 animate-spin mr-2" />
                          ) : null}
                          {isCurrentPlan
                            ? t('billing.currentPlan')
                            : t('billing.selectPlan')}
                        </Button>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
            </div>

            {/* How Billing Works Section */}
            <Card className="border border-slate-700 bg-slate-800/50 mt-4">
              <CardContent className="p-6">
                <h3 className="font-semibold text-white mb-4 flex items-center gap-2">
                  <Info className="w-5 h-5 text-cyan-400" />
                  {t('billing.howBillingWorks')}
                </h3>
                <div className="space-y-3 text-sm text-slate-400">
                  <p>
                    <strong className="text-slate-300">{t('billing.phoneNumberInfo')}</strong>{' '}
                    {t('billing.phoneNumberInfoDesc')}
                  </p>
                  <p>
                    <strong className="text-slate-300">{t('billing.trialInfo')}</strong>{' '}
                    {t('billing.trialInfoDesc')}
                  </p>
                  <p>
                    <strong className="text-slate-300">{t('billing.overageInfo')}</strong>{' '}
                    {t('billing.overageInfoDesc')}
                  </p>
                </div>
              </CardContent>
            </Card>
          </div>
        </main>
      </div>
    </SidebarProvider>
  );
}
