
import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Badge } from "@/components/ui/badge";
import {
  Store,
  PhoneCall,
  CreditCard,
  Check,
  ArrowRight,
  ArrowLeft,
  Zap,
  Crown,
  Star,
  Shield,
  Globe,
  Loader2
} from "lucide-react";
import { useTranslation } from "react-i18next";

interface PhoneNumber {
  id: string;
  phone_number: string;
  country_code: string;
  country_name: string;
  location: string | null;
  phone_type: string;
  is_available: boolean;
}

export function OnboardingContent() {
  const { t } = useTranslation();
  const [currentStep, setCurrentStep] = useState(1);
  const [shopifyUrl, setShopifyUrl] = useState("");
  const [selectedPhone, setSelectedPhone] = useState("");
  const [selectedPackage, setSelectedPackage] = useState("free-trial");
  const [phoneNumbers, setPhoneNumbers] = useState<PhoneNumber[]>([]);
  const [loadingPhoneNumbers, setLoadingPhoneNumbers] = useState(false);
  const [phoneNumbersError, setPhoneNumbersError] = useState<string | null>(null);

  const packages = [
    {
      id: "free-trial",
      name: t('onboarding.step3.packages.freeTrial.name'),
      price: t('onboarding.step3.packages.freeTrial.price'),
      period: t('onboarding.step3.packages.freeTrial.period'),
      description: t('onboarding.step3.packages.freeTrial.description'),
      features: t('onboarding.step3.packages.freeTrial.features', { returnObjects: true }) as string[],
      badge: t('onboarding.step3.packages.freeTrial.badge'),
      badgeColor: "bg-green-500"
    },
    {
      id: "starter",
      name: t('onboarding.step3.packages.starter.name'),
      price: t('onboarding.step3.packages.starter.price'),
      period: t('onboarding.step3.packages.starter.period'),
      description: t('onboarding.step3.packages.starter.description'),
      features: t('onboarding.step3.packages.starter.features', { returnObjects: true }) as string[],
      badge: null,
      badgeColor: ""
    },
    {
      id: "professional",
      name: t('onboarding.step3.packages.professional.name'),
      price: t('onboarding.step3.packages.professional.price'),
      period: t('onboarding.step3.packages.professional.period'),
      description: t('onboarding.step3.packages.professional.description'),
      features: t('onboarding.step3.packages.professional.features', { returnObjects: true }) as string[],
      badge: t('onboarding.step3.packages.professional.badge'),
      badgeColor: "bg-purple-500"
    }
  ];

  // Fetch phone numbers when component mounts or step changes to 2
  useEffect(() => {
    if (currentStep === 2 && phoneNumbers.length === 0) {
      fetchPhoneNumbers();
    }
  }, [currentStep]);

  const fetchPhoneNumbers = async () => {
    setLoadingPhoneNumbers(true);
    setPhoneNumbersError(null);

    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        setPhoneNumbersError('Not authenticated');
        return;
      }

      const session = JSON.parse(sessionData);
      const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:54321/functions/v1';

      const response = await fetch(`${apiUrl}/api/phone-numbers`, {
        headers: {
          'Authorization': `Bearer ${session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch phone numbers');
      }

      const data = await response.json();

      if (data.success && data.phone_numbers) {
        setPhoneNumbers(data.phone_numbers);
      } else {
        setPhoneNumbersError('No phone numbers available');
      }
    } catch (error) {
      console.error('Error fetching phone numbers:', error);
      setPhoneNumbersError('Failed to load phone numbers');
    } finally {
      setLoadingPhoneNumbers(false);
    }
  };

  const nextStep = () => {
    if (currentStep < 3) {
      setCurrentStep(currentStep + 1);
    }
  };

  const prevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleFinish = () => {
    console.log("Onboarding completed:", {
      shopifyUrl,
      selectedPhone,
      selectedPackage
    });
    // Redirect to dashboard or show success
    window.location.href = "/";
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 p-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="flex items-center justify-center gap-2 mb-6">
            <div className="w-12 h-12 bg-cyan-500 rounded-xl flex items-center justify-center">
              <PhoneCall className="w-6 h-6 text-white" />
            </div>
            <h1 className="text-3xl font-bold text-white">{t('onboarding.title')}</h1>
          </div>
          <p className="text-slate-400 text-lg">{t('onboarding.subtitle')}</p>
        </div>

        {/* Progress Steps */}
        <div className="flex items-center justify-center mb-12">
          <div className="flex items-center gap-4">
            {[1, 2, 3].map((step) => (
              <div key={step} className="flex items-center">
                <div className={`w-12 h-12 rounded-full flex items-center justify-center font-semibold ${
                  currentStep >= step 
                    ? "bg-cyan-500 text-white" 
                    : "bg-slate-700 text-slate-400"
                }`}>
                  {currentStep > step ? <Check className="w-5 h-5" /> : step}
                </div>
                {step < 3 && (
                  <div className={`w-16 h-1 mx-2 ${
                    currentStep > step ? "bg-cyan-500" : "bg-slate-700"
                  }`} />
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Step Content */}
        <Card className="bg-slate-800 border-slate-700 mb-8">
          <CardHeader>
            <div className="flex items-center gap-3">
              {currentStep === 1 && <Store className="w-6 h-6 text-cyan-500" />}
              {currentStep === 2 && <PhoneCall className="w-6 h-6 text-cyan-500" />}
              {currentStep === 3 && <CreditCard className="w-6 h-6 text-cyan-500" />}
              <CardTitle className="text-white">
                {currentStep === 1 && t('onboarding.step1.title')}
                {currentStep === 2 && t('onboarding.step2.title')}
                {currentStep === 3 && t('onboarding.step3.title')}
              </CardTitle>
            </div>
            <p className="text-slate-400">
              {currentStep === 1 && t('onboarding.step1.subtitle')}
              {currentStep === 2 && t('onboarding.step2.subtitle')}
              {currentStep === 3 && t('onboarding.step3.subtitle')}
            </p>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Step 1: Connect Shopify */}
            {currentStep === 1 && (
              <div className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="shopify-url" className="text-white">{t('onboarding.step1.label')}</Label>
                  <Input
                    id="shopify-url"
                    placeholder={t('onboarding.step1.placeholder')}
                    value={shopifyUrl}
                    onChange={(e) => setShopifyUrl(e.target.value)}
                    className="bg-slate-700 border-slate-600 text-white"
                  />
                  <p className="text-slate-400 text-sm">{t('onboarding.step1.description')}</p>
                </div>

                <div className="bg-slate-700/50 p-6 rounded-lg">
                  <div className="flex items-start gap-3">
                    <Shield className="w-6 h-6 text-cyan-500 mt-1" />
                    <div>
                      <h4 className="text-white font-medium mb-2">{t('onboarding.step1.secureTitle')}</h4>
                      <ul className="text-slate-300 text-sm space-y-1">
                        {(t('onboarding.step1.securePoints', { returnObjects: true }) as string[]).map((point, idx) => (
                          <li key={idx}>• {point}</li>
                        ))}
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Step 2: Phone Number Selection */}
            {currentStep === 2 && (
              <div className="space-y-6">
                {loadingPhoneNumbers ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="w-8 h-8 text-cyan-500 animate-spin" />
                    <span className="ml-3 text-slate-400">{t('onboarding.step2.loading')}</span>
                  </div>
                ) : phoneNumbersError ? (
                  <div className="bg-red-500/10 border border-red-500 rounded-lg p-4">
                    <p className="text-red-500">{t('onboarding.step2.error')}</p>
                    <Button
                      onClick={fetchPhoneNumbers}
                      className="mt-4 bg-cyan-500 hover:bg-cyan-600"
                    >
                      {t('common.tryAgain')}
                    </Button>
                  </div>
                ) : phoneNumbers.length === 0 ? (
                  <div className="bg-yellow-500/10 border border-yellow-500 rounded-lg p-4">
                    <p className="text-yellow-500">{t('onboarding.step2.noPhones')}</p>
                  </div>
                ) : (
                  <>
                    <RadioGroup value={selectedPhone} onValueChange={setSelectedPhone}>
                      <div className="grid gap-4">
                        {phoneNumbers.map((phone) => (
                          <div key={phone.id} className="flex items-center space-x-3">
                            <RadioGroupItem value={phone.phone_number} id={phone.id} />
                            <Label
                              htmlFor={phone.id}
                              className="flex-1 cursor-pointer"
                            >
                              <Card className="bg-slate-700 border-slate-600 hover:border-cyan-500 transition-colors">
                                <CardContent className="p-4">
                                  <div className="flex items-center justify-between">
                                    <div>
                                      <div className="text-white font-mono text-lg">{phone.phone_number}</div>
                                      <div className="text-slate-400 text-sm flex items-center gap-2">
                                        <Globe className="w-4 h-4" />
                                        {phone.location || phone.country_name}
                                      </div>
                                    </div>
                                    <Badge
                                      className={phone.phone_type === "toll-free" ? "bg-purple-500" : "bg-green-500"}
                                    >
                                      {phone.phone_type}
                                    </Badge>
                                  </div>
                                </CardContent>
                              </Card>
                            </Label>
                          </div>
                        ))}
                      </div>
                    </RadioGroup>

                    <div className="bg-slate-700/50 p-4 rounded-lg">
                      <p className="text-slate-300 text-sm">
                        <strong>Note:</strong> Your selected phone number will be instantly activated and ready to receive calls.
                        You can always add more numbers later from your dashboard.
                      </p>
                    </div>
                  </>
                )}
              </div>
            )}

            {/* Step 3: Package Selection */}
            {currentStep === 3 && (
              <div className="space-y-6">
                <RadioGroup value={selectedPackage} onValueChange={setSelectedPackage}>
                  <div className="grid gap-6 md:grid-cols-3">
                    {packages.map((pkg) => (
                      <div key={pkg.id} className="flex items-start space-x-3">
                        <RadioGroupItem value={pkg.id} id={pkg.id} className="mt-6" />
                        <Label htmlFor={pkg.id} className="flex-1 cursor-pointer">
                          <Card className={`bg-slate-700 border-slate-600 hover:border-cyan-500 transition-colors relative ${
                            selectedPackage === pkg.id ? "ring-2 ring-cyan-500" : ""
                          }`}>
                            {pkg.badge && (
                              <div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
                                <Badge className={`${pkg.badgeColor} text-white`}>
                                  {pkg.badge}
                                </Badge>
                              </div>
                            )}
                            <CardHeader className="text-center">
                              <div className="flex items-center justify-center mb-2">
                                {pkg.id === "free-trial" && <Zap className="w-6 h-6 text-green-500" />}
                                {pkg.id === "starter" && <Star className="w-6 h-6 text-blue-500" />}
                                {pkg.id === "professional" && <Crown className="w-6 h-6 text-purple-500" />}
                              </div>
                              <CardTitle className="text-white">{pkg.name}</CardTitle>
                              <div className="text-3xl font-bold text-cyan-500">
                                {pkg.price}
                                <span className="text-sm text-slate-400">/{pkg.period}</span>
                              </div>
                              <p className="text-slate-400 text-sm">{pkg.description}</p>
                            </CardHeader>
                            <CardContent>
                              <ul className="space-y-2">
                                {pkg.features.map((feature, index) => (
                                  <li key={index} className="flex items-center gap-2 text-slate-300 text-sm">
                                    <Check className="w-4 h-4 text-green-500" />
                                    {feature}
                                  </li>
                                ))}
                              </ul>
                            </CardContent>
                          </Card>
                        </Label>
                      </div>
                    ))}
                  </div>
                </RadioGroup>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Navigation Buttons */}
        <div className="flex items-center justify-between">
          <Button
            variant="outline"
            onClick={prevStep}
            disabled={currentStep === 1}
            className="text-slate-400 border-slate-600 hover:bg-slate-700"
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            {t('onboarding.back')}
          </Button>

          {currentStep < 3 ? (
            <Button
              onClick={nextStep}
              disabled={
                (currentStep === 1 && !shopifyUrl) ||
                (currentStep === 2 && !selectedPhone)
              }
              className="bg-cyan-500 hover:bg-cyan-600 text-white"
            >
              {t('onboarding.next')}
              <ArrowRight className="w-4 h-4 ml-2" />
            </Button>
          ) : (
            <Button
              onClick={handleFinish}
              className="bg-green-500 hover:bg-green-600 text-white"
            >
              {t('onboarding.finish')}
              <Check className="w-4 h-4 ml-2" />
            </Button>
          )}
        </div>

        {/* Footer */}
        <div className="text-center mt-12 text-slate-500 text-sm">
          <p>Need help? Contact our support team or check our documentation</p>
        </div>
      </div>
    </div>
  );
}
