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 { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useTranslation } from 'react-i18next';
import { useShop } from "@/components/context/ShopContext";
import { useSubscription, useUpdateSubscription } from "@/hooks/useSubscription";
import { usePlans, usePackages } from "@/hooks/usePlans";
import {
  Zap,
  Star,
  TrendingUp,
  Crown,
  Check,
  Phone,
  Clock,
  AlertCircle,
  Loader2,
  Info
} from "lucide-react";
import {
  getPlanPrice,
  getPackagePrice,
  formatCurrency,
  getUsageProgressColor,
  type Currency,
  type PlanWithTranslation,
  type PackageWithTranslation
} 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 Billing() {
  const { t } = useTranslation();
  const { selectedShop } = useShop();
  const [selectedPlanId, setSelectedPlanId] = useState<string | null>(null);
  const [isChangingPlan, setIsChangingPlan] = useState(false);

  // Hooks
  const {
    subscription,
    isLoading: subLoading,
    minutesRemaining,
    packageMinutesRemaining,
    totalMinutesRemaining,
    usagePercentage,
    isExpired,
    daysRemaining,
    refetch: refetchSubscription
  } = useSubscription(selectedShop?.id);

  const { plans, isLoading: plansLoading } = usePlans();
  const { packages, purchasePackage, isLoading: packagesLoading } = usePackages();
  const { changePlan, updateAutoPurchase, 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);
  };

  // Handle package purchase
  const handlePurchasePackage = async (pkg: PackageWithTranslation) => {
    if (!selectedShop?.id || !subscription?.id) return;

    const success = await purchasePackage(
      selectedShop.id,
      subscription.id,
      pkg.id,
      pkg,
      currentCurrency
    );

    if (success) {
      await refetchSubscription();
    }
  };

  // Handle auto-purchase toggle
  const handleAutoPurchaseToggle = async (enabled: boolean) => {
    if (!selectedShop?.id) return;

    await updateAutoPurchase(
      selectedShop.id,
      enabled,
      subscription?.auto_purchase_package_id || packages[0]?.id,
      subscription?.auto_purchase_threshold || 5
    );

    await refetchSubscription();
  };

  // 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">+ ÁFA</p>

                        {/* Features List */}
                        <div className="space-y-3 pt-2">
                          {plan.features.map((feature, idx) => (
                            <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>

            {/* Additional Packages Section */}
            {subscription && subscription.status !== 'trial' && (
              <div className="mt-8">
                <h2 className="text-xl font-semibold text-white mb-4">
                  {t('billing.additionalPackages')}
                </h2>
                <p className="text-slate-400 mb-6">
                  {t('billing.additionalPackagesDescription')}
                </p>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  {packages.map(pkg => (
                    <Card
                      key={pkg.id}
                      className="border border-slate-700 bg-slate-800/50 hover:border-cyan-500/50 transition-all"
                    >
                      <CardContent className="p-4">
                        <div className="flex items-center justify-between mb-3">
                          <div className="flex items-center gap-2">
                            <Clock className="w-5 h-5 text-cyan-400" />
                            <span className="font-semibold text-white">
                              {pkg.translations.name}
                            </span>
                          </div>
                          <span className="text-lg font-bold text-white">
                            {formatCurrency(getPackagePrice(pkg, currentCurrency), currentCurrency)}
                          </span>
                        </div>
                        <p className="text-sm text-slate-400 mb-4">
                          {pkg.translations.description}
                        </p>
                        <Button
                          variant="outline"
                          className="w-full border-cyan-500 text-cyan-400 hover:bg-cyan-500/10"
                          onClick={() => handlePurchasePackage(pkg)}
                        >
                          {t('billing.purchasePackage')}
                        </Button>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </div>
            )}

            {/* Auto-Purchase Settings */}
            {subscription && subscription.status !== 'trial' && (
              <Card className="border border-slate-700 bg-slate-800/50 mt-4">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="font-semibold text-white">
                        {t('billing.autoPurchase')}
                      </h3>
                      <p className="text-sm text-slate-400 mt-1">
                        {t('billing.autoPurchaseDescription')}
                      </p>
                    </div>
                    <Switch
                      checked={subscription.auto_purchase_enabled}
                      onCheckedChange={handleAutoPurchaseToggle}
                    />
                  </div>

                  {subscription.auto_purchase_enabled && (
                    <div className="mt-4 pt-4 border-t border-slate-700 grid grid-cols-2 gap-4">
                      <div>
                        <label className="text-sm text-slate-400 mb-2 block">
                          {t('billing.autoPurchasePackage')}
                        </label>
                        <Select
                          value={subscription.auto_purchase_package_id || ''}
                          onValueChange={(value) => {
                            if (selectedShop?.id) {
                              updateAutoPurchase(
                                selectedShop.id,
                                true,
                                value,
                                subscription.auto_purchase_threshold
                              );
                            }
                          }}
                        >
                          <SelectTrigger className="bg-slate-700 border-slate-600">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent className="bg-slate-800 border-slate-600">
                            {packages.map(pkg => (
                              <SelectItem key={pkg.id} value={pkg.id} className="text-white">
                                {pkg.translations.name} - {formatCurrency(getPackagePrice(pkg, currentCurrency), currentCurrency)}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <label className="text-sm text-slate-400 mb-2 block">
                          {t('billing.autoPurchaseThreshold')}
                        </label>
                        <Select
                          value={String(subscription.auto_purchase_threshold)}
                          onValueChange={(value) => {
                            if (selectedShop?.id) {
                              updateAutoPurchase(
                                selectedShop.id,
                                true,
                                subscription.auto_purchase_package_id || packages[0]?.id,
                                parseInt(value)
                              );
                            }
                          }}
                        >
                          <SelectTrigger className="bg-slate-700 border-slate-600">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent className="bg-slate-800 border-slate-600">
                            {[1, 2, 5, 10, 15, 20].map(mins => (
                              <SelectItem key={mins} value={String(mins)} className="text-white">
                                {mins} {t('billing.minutesRemaining')}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            {/* 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>
  );
}
