
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Mic, MessageSquare, Store, Loader2 } from "lucide-react";
import { useState, useEffect } from "react";
import { API_URL } from "@/lib/config";
import { useToast } from "@/hooks/use-toast";
import { useTranslation } from "react-i18next";
import { useShop } from "@/components/context/ShopContext";

interface AIConfig {
  voice_type: string;
  speaking_speed: string;
  accent_language: string;
  greeting_message: string;
  business_hours_mode: boolean;
  local_currency_support: boolean;
  escalation_policy: string;
}

export function AIConfigContent() {
  const { t } = useTranslation();
  const { toast } = useToast();
  const { selectedShop, stores, isLoading } = useShop();
  const [saving, setSaving] = useState(false);
  const [aiConfig, setAiConfig] = useState<AIConfig>({
    voice_type: "sarah",
    speaking_speed: "normal",
    accent_language: "us-english",
    greeting_message: "",
    business_hours_mode: true,
    local_currency_support: true,
    escalation_policy: "medium"
  });

  // Load AI config when selected shop changes
  useEffect(() => {
    if (selectedShop) {
      loadAIConfig(selectedShop);
    }
  }, [selectedShop]);

  const loadAIConfig = (store: any) => {
    // Load AI config from store's alt_data or use defaults
    const config = store.alt_data?.ai_config || {};

    setAiConfig({
      voice_type: config.voice_type || "sarah",
      speaking_speed: config.speaking_speed || "normal",
      accent_language: config.accent_language || "us-english",
      greeting_message: config.greeting_message || `Hello! Thank you for calling ${store.store_name || 'our store'}. I'm your AI assistant, and I'm here to help you with any questions about your order or our products. How can I assist you today?`,
      business_hours_mode: config.business_hours_mode !== undefined ? config.business_hours_mode : true,
      local_currency_support: config.local_currency_support !== undefined ? config.local_currency_support : true,
      escalation_policy: config.escalation_policy || "medium"
    });
  };

  const handleSaveConfig = async () => {
    if (!selectedShop) return;

    setSaving(true);
    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);

      // Update store's alt_data with AI config
      const response = await fetch(`${API_URL}/api/stores/${selectedShop.id}/ai-config`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ ai_config: aiConfig })
      });

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

      toast({
        title: t('common.success'),
        description: t('aiConfig.saveConfiguration'),
      });
    } catch (error) {
      console.error('Error saving config:', error);
      toast({
        title: t('common.error'),
        description: t('common.tryAgain'),
        variant: "destructive"
      });
    } finally {
      setSaving(false);
    }
  };

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

  if (stores.length === 0) {
    return (
      <div className="flex-1 space-y-6 p-8 bg-slate-900">
        <div className="flex items-center justify-center min-h-[60vh]">
          <div className="text-center">
            <Store className="w-16 h-16 text-slate-600 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-white mb-2">{t('aiConfig.noStoresConnected.title')}</h3>
            <p className="text-slate-400 mb-6">
              {t('aiConfig.noStoresConnected.description')}
            </p>
            <Button
              className="bg-cyan-500 hover:bg-cyan-600 text-white"
              onClick={() => window.location.href = '/webshops'}
            >
              {t('aiConfig.noStoresConnected.goToWebshops')}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  if (!selectedShop) {
    return (
      <div className="flex-1 flex items-center justify-center min-h-screen bg-slate-900">
        <p className="text-slate-400">No store selected</p>
      </div>
    );
  }

  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('aiConfig.title')}</h2>
          <p className="text-slate-400">{t('aiConfig.subtitle')}</p>
        </div>
        <div className="flex gap-3">
          <Button
            className="bg-cyan-500 hover:bg-cyan-600 text-white"
            onClick={handleSaveConfig}
            disabled={saving}
          >
            {saving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                {t('aiConfig.saving')}
              </>
            ) : (
              t('aiConfig.saveConfiguration')
            )}
          </Button>
        </div>
      </div>

      <div className="grid gap-6">
        <Card className="bg-slate-800 border-slate-700">
          <CardHeader>
            <div className="flex items-center gap-3">
              <Mic className="w-6 h-6 text-cyan-500" />
              <CardTitle className="text-white">{t('aiConfig.voiceSettings.title')}</CardTitle>
            </div>
            <p className="text-slate-400">{t('aiConfig.voiceSettings.subtitle')} {selectedShop.store_name || 'your store'}</p>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid gap-6 md:grid-cols-2">
              <div className="space-y-2">
                <Label className="text-slate-300">{t('aiConfig.voiceSettings.voiceType')}</Label>
                <Select value={aiConfig.voice_type} onValueChange={(value) => setAiConfig({ ...aiConfig, voice_type: value })}>
                  <SelectTrigger className="bg-slate-700 border-slate-600 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-slate-700 border-slate-600">
                    <SelectItem value="sarah">{t('aiConfig.voiceSettings.voices.sarah')}</SelectItem>
                    <SelectItem value="james">{t('aiConfig.voiceSettings.voices.james')}</SelectItem>
                    <SelectItem value="emma">{t('aiConfig.voiceSettings.voices.emma')}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label className="text-slate-300">{t('aiConfig.voiceSettings.speakingSpeed')}</Label>
                <Select value={aiConfig.speaking_speed} onValueChange={(value) => setAiConfig({ ...aiConfig, speaking_speed: value })}>
                  <SelectTrigger className="bg-slate-700 border-slate-600 text-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="bg-slate-700 border-slate-600">
                    <SelectItem value="slow">{t('aiConfig.voiceSettings.speeds.slow')}</SelectItem>
                    <SelectItem value="normal">{t('aiConfig.voiceSettings.speeds.normal')}</SelectItem>
                    <SelectItem value="fast">{t('aiConfig.voiceSettings.speeds.fast')}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <Label className="text-slate-300">{t('aiConfig.voiceSettings.accentLanguage')}</Label>
              <Select value={aiConfig.accent_language} onValueChange={(value) => setAiConfig({ ...aiConfig, accent_language: value })}>
                <SelectTrigger className="bg-slate-700 border-slate-600 text-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-slate-700 border-slate-600">
                  <SelectItem value="us-english">{t('aiConfig.voiceSettings.accents.usEnglish')}</SelectItem>
                  <SelectItem value="uk-english">{t('aiConfig.voiceSettings.accents.ukEnglish')}</SelectItem>
                  <SelectItem value="australian">{t('aiConfig.voiceSettings.accents.australian')}</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-slate-800 border-slate-700">
          <CardHeader>
            <div className="flex items-center gap-3">
              <MessageSquare className="w-6 h-6 text-cyan-500" />
              <CardTitle className="text-white">{t('aiConfig.conversationBehavior.title')}</CardTitle>
            </div>
            <p className="text-slate-400">{t('aiConfig.conversationBehavior.subtitle')} {selectedShop.store_name || 'your store'} customers</p>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-2">
              <Label className="text-slate-300">{t('aiConfig.conversationBehavior.greetingMessage')}</Label>
              <Textarea
                className="bg-slate-700 border-slate-600 text-white min-h-[100px]"
                value={aiConfig.greeting_message}
                onChange={(e) => setAiConfig({ ...aiConfig, greeting_message: e.target.value })}
              />
            </div>

            <div className="grid gap-6 md:grid-cols-2">
              <div className="flex items-center justify-between">
                <div className="space-y-1">
                  <Label className="text-slate-300">{t('aiConfig.conversationBehavior.businessHoursMode')}</Label>
                  <p className="text-sm text-slate-400">{t('aiConfig.conversationBehavior.businessHoursModeDesc')}</p>
                </div>
                <Switch
                  checked={aiConfig.business_hours_mode}
                  onCheckedChange={(checked) => setAiConfig({ ...aiConfig, business_hours_mode: checked })}
                  className="data-[state=checked]:bg-cyan-500"
                />
              </div>
              <div className="flex items-center justify-between">
                <div className="space-y-1">
                  <Label className="text-slate-300">{t('aiConfig.conversationBehavior.localCurrencySupport')}</Label>
                  <p className="text-sm text-slate-400">{t('aiConfig.conversationBehavior.localCurrencySupportDesc')}</p>
                </div>
                <Switch
                  checked={aiConfig.local_currency_support}
                  onCheckedChange={(checked) => setAiConfig({ ...aiConfig, local_currency_support: checked })}
                  className="data-[state=checked]:bg-cyan-500"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label className="text-slate-300">{t('aiConfig.conversationBehavior.escalationPolicy')}</Label>
              <Select value={aiConfig.escalation_policy} onValueChange={(value) => setAiConfig({ ...aiConfig, escalation_policy: value })}>
                <SelectTrigger className="bg-slate-700 border-slate-600 text-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-slate-700 border-slate-600">
                  <SelectItem value="low">{t('aiConfig.conversationBehavior.escalationPolicies.low')}</SelectItem>
                  <SelectItem value="medium">{t('aiConfig.conversationBehavior.escalationPolicies.medium')}</SelectItem>
                  <SelectItem value="high">{t('aiConfig.conversationBehavior.escalationPolicies.high')}</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
