import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { PhoneCall, Plus, Settings, AlertTriangle, CheckCircle, Clock, Link, Shield, Loader2 } from "lucide-react";
import { API_URL } from "@/lib/config";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useTranslation } from "react-i18next";

interface PhoneNumber {
  id: string;
  phone_number: string;
  country_code: string;
  country_name: string;
  location: string;
  phone_type: string;
  price: number;
  is_available: boolean;
}

interface Store {
  id: string;
  store_name: string;
  platform_name: string;
  store_url: string;
  is_active: boolean;
  connected_at: string;
  phone_numbers?: PhoneNumber;
}

const availableCountries = [
  {
    name: "United States",
    flag: "🇺🇸",
    pricing: {
      setup: "0 HUF",
      monthly: "1,800 HUF/hónap"
    },
    kycRequired: false,
    availability: "Instant"
  },
  {
    name: "United Kingdom",
    flag: "🇬🇧",
    pricing: {
      setup: "0 HUF",
      monthly: "2,880 HUF/hónap"
    },
    kycRequired: true,
    availability: "2-3 business days"
  },
  {
    name: "Canada",
    flag: "🇨🇦",
    pricing: {
      setup: "0 HUF",
      monthly: "2,160 HUF/hónap"
    },
    kycRequired: false,
    availability: "Instant"
  },
  {
    name: "Australia",
    flag: "🇦🇺",
    pricing: {
      setup: "0 HUF",
      monthly: "3,600 HUF/hónap"
    },
    kycRequired: true,
    availability: "1-2 business days"
  }
];

const carriers = [
  {
    name: "Twilio",
    logo: "📞",
    description: "Global communications platform",
    features: ["Global coverage", "99.99% uptime", "Advanced analytics"],
    setupFields: ["Account SID", "Auth Token", "Phone Number SID"]
  },
  {
    name: "Telnyx",
    logo: "📡",
    description: "Modern telecom infrastructure",
    features: ["Low latency", "Real-time APIs", "Global network"],
    setupFields: ["API Key", "Phone Number ID", "Connection ID"]
  },
  {
    name: "Vonage",
    logo: "🌐",
    description: "Cloud communications APIs",
    features: ["Voice & SMS", "Global reach", "Enterprise grade"],
    setupFields: ["API Key", "API Secret", "Application ID"]
  },
  {
    name: "Zadarma",
    logo: "☎️",
    description: "Business telephony solutions",
    features: ["Cost effective", "Easy setup", "Multi-country"],
    setupFields: ["User Key", "Secret Key", "Phone Number"]
  }
];

export function PhoneNumbersContent() {
  const { t } = useTranslation();
  const [stores, setStores] = useState<Store[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>("");

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

  const fetchStores = async () => {
    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        setError('Authentication required. Please log in again.');
        setLoading(false);
        return;
      }

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/api/stores`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

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

      const data = await response.json();
      if (data.success) {
        setStores(data.stores || []);
      } else {
        setError('Failed to load stores');
      }
    } catch (err) {
      console.error('Error fetching stores:', err);
      setError('Failed to load stores. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const getPlatformDisplayName = (platform: string) => {
    const platformMap: { [key: string]: string } = {
      'shopify': 'Shopify',
      'woocommerce': 'WooCommerce',
      'shoprenter': 'ShopRenter'
    };
    return platformMap[platform.toLowerCase()] || platform;
  };

  const getStatusBadge = (store: Store) => {
    if (!store.is_active) {
      return { text: t('phoneNumbers.table.inactive'), color: "bg-red-500" };
    }
    if (!store.phone_numbers) {
      return { text: t('phoneNumbers.table.noPhoneNumber'), color: "bg-yellow-500" };
    }
    return { text: t('phoneNumbers.table.active'), color: "bg-green-500" };
  };

  const activeStoresCount = stores.filter(s => s.is_active && s.phone_numbers).length;

  return (
    <div className="flex-1 space-y-6 p-8 bg-slate-900">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold tracking-tight text-white">{t('phoneNumbers.title')}</h2>
          <p className="text-slate-400">{t('phoneNumbers.subtitle')}</p>
        </div>
        <Button
          className="bg-slate-600 hover:bg-slate-600 text-slate-400 cursor-not-allowed"
          disabled
        >
          <Plus className="w-4 h-4 mr-2" />
          {t('phoneNumbers.addPhoneNumber')}
        </Button>
      </div>

      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h3 className="text-xl font-semibold text-white">{t('phoneNumbers.webshopPhoneNumbers')}</h3>
          <p className="text-slate-400">
            {loading ? t('common.loading') : `${stores.length} ${stores.length !== 1 ? t('phoneNumbers.webshopsCountPlural') : t('phoneNumbers.webshopsCount')} • ${activeStoresCount} ${activeStoresCount !== 1 ? t('phoneNumbers.activeNumberPlural') : t('phoneNumbers.activeNumber')}`}
          </p>
        </div>

        {error && (
          <Alert className="bg-red-500/10 border-red-500/50">
            <AlertTriangle className="h-4 w-4 text-red-500" />
            <AlertDescription className="text-red-500">
              {error}
            </AlertDescription>
          </Alert>
        )}

        {loading ? (
          <Card className="bg-slate-800 border-slate-700">
            <CardContent className="p-8">
              <div className="flex items-center justify-center gap-3">
                <Loader2 className="w-6 h-6 text-cyan-500 animate-spin" />
                <span className="text-slate-400">{t('phoneNumbers.loadingStores')}</span>
              </div>
            </CardContent>
          </Card>
        ) : stores.length === 0 ? (
          <Card className="bg-slate-800 border-slate-700">
            <CardContent className="p-8">
              <div className="text-center">
                <PhoneCall className="w-12 h-12 text-slate-600 mx-auto mb-4" />
                <h3 className="text-white text-lg font-semibold mb-2">{t('phoneNumbers.noWebshopsConnected')}</h3>
                <p className="text-slate-400 mb-4">{t('phoneNumbers.noWebshopsSubtitle')}</p>
                <Button className="bg-cyan-500 hover:bg-cyan-600 text-white" onClick={() => window.location.href = '/webshops'}>
                  {t('phoneNumbers.goToWebshops')}
                </Button>
              </div>
            </CardContent>
          </Card>
        ) : (
          <Card className="bg-slate-800 border-slate-700">
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="border-b border-slate-700">
                    <tr className="text-left">
                      <th className="p-4 text-slate-300 font-medium">{t('phoneNumbers.table.webshop')}</th>
                      <th className="p-4 text-slate-300 font-medium">{t('phoneNumbers.table.phoneNumber')}</th>
                      <th className="p-4 text-slate-300 font-medium">{t('phoneNumbers.table.country')}</th>
                      <th className="p-4 text-slate-300 font-medium">{t('phoneNumbers.table.type')}</th>
                      <th className="p-4 text-slate-300 font-medium">{t('phoneNumbers.table.status')}</th>
                      <th className="p-4 text-slate-300 font-medium">{t('phoneNumbers.table.actions')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {stores.map((store) => {
                      const statusBadge = getStatusBadge(store);
                      const phoneNumber = store.phone_numbers;

                      return (
                        <tr key={store.id} className="border-b border-slate-700/50 hover:bg-slate-700/30">
                          <td className="p-4">
                            <div>
                              <div className="text-white font-medium">{store.store_name || store.store_url}</div>
                              <div className="text-slate-400 text-sm">{getPlatformDisplayName(store.platform_name)}</div>
                            </div>
                          </td>
                          <td className="p-4">
                            <div className="flex items-center gap-2">
                              <PhoneCall className="w-4 h-4 text-slate-400" />
                              <span className={`text-sm ${phoneNumber ? "text-white font-mono" : "text-slate-500 italic"}`}>
                                {phoneNumber ? phoneNumber.phone_number : t('phoneNumbers.table.notAssigned')}
                              </span>
                            </div>
                          </td>
                          <td className="p-4 text-slate-300">
                            {phoneNumber ? `${phoneNumber.country_name} (${phoneNumber.location})` : "-"}
                          </td>
                          <td className="p-4">
                            {phoneNumber ? (
                              <Badge
                                variant={phoneNumber.price === 0 ? "default" : "secondary"}
                                className={phoneNumber.price === 0 ? "bg-green-600 text-white" : "bg-purple-600 text-white"}
                              >
                                {phoneNumber.price === 0 ? t('phoneNumbers.table.free') : t('phoneNumbers.table.premium')}
                              </Badge>
                            ) : (
                              <span className="text-slate-500">-</span>
                            )}
                          </td>
                          <td className="p-4">
                            <Badge className={`${statusBadge.color} text-white`}>
                              {statusBadge.text}
                            </Badge>
                          </td>
                          <td className="p-4">
                            <div className="flex items-center gap-2">
                              {phoneNumber ? (
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="text-slate-400 hover:text-slate-400 cursor-not-allowed"
                                  disabled
                                >
                                  <Settings className="w-4 h-4" />
                                </Button>
                              ) : (
                                <Button
                                  size="sm"
                                  className="bg-slate-600 hover:bg-slate-600 text-slate-400 cursor-not-allowed"
                                  disabled
                                >
                                  <Plus className="w-4 h-4 mr-1" />
                                  {t('phoneNumbers.table.assign')}
                                </Button>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        )}

        <div className="space-y-4 opacity-60">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-xl font-semibold text-white">{t('phoneNumbers.byoc.title')}</h3>
              <p className="text-slate-400">{t('phoneNumbers.byoc.subtitle')}</p>
            </div>
            <Badge variant="outline" className="text-slate-400 border-slate-600">{t('phoneNumbers.byoc.comingSoon')}</Badge>
          </div>

          <div className="grid gap-6 md:grid-cols-2">
            {carriers.map((carrier, index) => (
              <Card key={index} className="bg-slate-800 border-slate-700 opacity-75">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <span className="text-2xl">{carrier.logo}</span>
                      <div>
                        <CardTitle className="text-white">{carrier.name}</CardTitle>
                        <p className="text-slate-400 text-sm">{carrier.description}</p>
                      </div>
                    </div>
                    <Button className="bg-slate-600 text-slate-400 cursor-not-allowed" disabled>
                      <Link className="w-4 h-4 mr-2" />
                      {t('phoneNumbers.byoc.connect')}
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <div className="space-y-2">
                      <h5 className="text-sm font-medium text-white">{t('phoneNumbers.byoc.features')}</h5>
                      <ul className="space-y-1">
                        {carrier.features.map((feature, idx) => (
                          <li key={idx} className="flex items-center gap-2">
                            <CheckCircle className="w-3 h-3 text-green-500" />
                            <span className="text-xs text-slate-300">{feature}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                    <div className="space-y-2">
                      <h5 className="text-sm font-medium text-white">{t('phoneNumbers.byoc.requiredFields')}</h5>
                      <div className="text-xs text-slate-400">
                        {carrier.setupFields.join(", ")}
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>

        <div className="space-y-4 opacity-60">
          <div className="flex items-center justify-between">
            <h3 className="text-xl font-semibold text-white">{t('phoneNumbers.availableCountries.title')}</h3>
            <Badge variant="outline" className="text-slate-400 border-slate-600">{t('phoneNumbers.byoc.comingSoon')}</Badge>
          </div>
          <div className="grid gap-6 md:grid-cols-2">
            {availableCountries.map((country, index) => (
              <Card key={index} className="bg-slate-800 border-slate-700 opacity-75">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <span className="text-2xl">{country.flag}</span>
                      <div>
                        <CardTitle className="text-white">{country.name}</CardTitle>
                        <p className="text-slate-400 text-sm">{t('phoneNumbers.availableCountries.setup')}: {country.pricing.setup} • {t('phoneNumbers.availableCountries.monthly')}: {country.pricing.monthly}</p>
                      </div>
                    </div>
                    <Button className="bg-slate-600 text-slate-400 cursor-not-allowed" disabled>
                      {t('phoneNumbers.availableCountries.getNumber')}
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <div className="flex items-center gap-2">
                      {country.kycRequired ? (
                        <AlertTriangle className="w-4 h-4 text-yellow-500" />
                      ) : (
                        <CheckCircle className="w-4 h-4 text-green-500" />
                      )}
                      <span className="text-sm text-slate-300">
                        {country.kycRequired ? t('phoneNumbers.availableCountries.kycRequired') : t('phoneNumbers.availableCountries.noVerification')}
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Clock className="w-4 h-4 text-blue-500" />
                      <span className="text-sm text-slate-300">
                        {t('phoneNumbers.availableCountries.activation')}: {country.availability}
                      </span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>

        <Card className="bg-slate-800 border-slate-700">
          <CardHeader>
            <div className="flex items-center gap-3">
              <PhoneCall className="w-6 h-6 text-cyan-500" />
              <CardTitle className="text-white">{t('phoneNumbers.setupGuide.title')}</CardTitle>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-4">
              <div className="flex gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-cyan-500 text-white rounded-full flex items-center justify-center font-semibold">1</div>
                <div>
                  <h4 className="text-white font-medium">{t('phoneNumbers.setupGuide.step1.title')}</h4>
                  <p className="text-slate-400">{t('phoneNumbers.setupGuide.step1.description')}</p>
                </div>
              </div>
              <div className="flex gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-cyan-500 text-white rounded-full flex items-center justify-center font-semibold">2</div>
                <div>
                  <h4 className="text-white font-medium">{t('phoneNumbers.setupGuide.step2.title')}</h4>
                  <p className="text-slate-400">{t('phoneNumbers.setupGuide.step2.description')}</p>
                </div>
              </div>
              <div className="flex gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-cyan-500 text-white rounded-full flex items-center justify-center font-semibold">3</div>
                <div>
                  <h4 className="text-white font-medium">{t('phoneNumbers.setupGuide.step3.title')}</h4>
                  <p className="text-slate-400">{t('phoneNumbers.setupGuide.step3.description')}</p>
                </div>
              </div>
              <div className="flex gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-cyan-500 text-white rounded-full flex items-center justify-center font-semibold">4</div>
                <div>
                  <h4 className="text-white font-medium">{t('phoneNumbers.setupGuide.step4.title')}</h4>
                  <p className="text-slate-400">{t('phoneNumbers.setupGuide.step4.description')}</p>
                </div>
              </div>
            </div>
            <div className="bg-slate-700/50 p-4 rounded-lg">
              <div className="flex items-start gap-3">
                <Shield className="w-5 h-5 text-blue-500 mt-0.5" />
                <div>
                  <h5 className="text-blue-500 font-medium">{t('phoneNumbers.setupGuide.carrierBenefits.title')}</h5>
                  <ul className="text-slate-300 text-sm mt-2 space-y-1">
                    <li>• {t('phoneNumbers.setupGuide.carrierBenefits.benefit1')}</li>
                    <li>• {t('phoneNumbers.setupGuide.carrierBenefits.benefit2')}</li>
                    <li>• {t('phoneNumbers.setupGuide.carrierBenefits.benefit3')}</li>
                    <li>• {t('phoneNumbers.setupGuide.carrierBenefits.benefit4')}</li>
                  </ul>
                </div>
              </div>
            </div>
            <div className="bg-slate-700/50 p-4 rounded-lg">
              <div className="flex items-start gap-3">
                <AlertTriangle className="w-5 h-5 text-yellow-500 mt-0.5" />
                <div>
                  <h5 className="text-yellow-500 font-medium">{t('phoneNumbers.setupGuide.importantNotes.title')}</h5>
                  <ul className="text-slate-300 text-sm mt-2 space-y-1">
                    <li>• {t('phoneNumbers.setupGuide.importantNotes.note1')}</li>
                    <li>• {t('phoneNumbers.setupGuide.importantNotes.note2')}</li>
                    <li>• {t('phoneNumbers.setupGuide.importantNotes.note3')}</li>
                    <li>• {t('phoneNumbers.setupGuide.importantNotes.note4')}</li>
                    <li>• {t('phoneNumbers.setupGuide.importantNotes.note5')}</li>
                  </ul>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
