import { BarChart, Code, Globe, Image, Loader2, Save } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import { seoApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';
import type { SEOSettings } from '@/types/seo';

export default function SEOSettingsPage() {
  const [settings, setSettings] = useState<Partial<SEOSettings>>({
    site_name: '',
    site_description: '',
    site_keywords: '',
    default_og_image: '',
    favicon_url: '',
    google_analytics_id: '',
    google_search_console_verification: '',
    facebook_app_id: '',
    twitter_handle: '',
    robots_txt: 'User-agent: *\nAllow: /',
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { toast } = useToast();

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

  const loadSettings = async () => {
    try {
      setLoading(true);
      const data = await seoApi.getSettings();
      if (data) {
        setSettings(data);
      }
    } catch (error) {
      console.error('SEO ayarları yükleme hatası:', error);
      toast({
        title: 'Hata',
        description: 'SEO ayarları yüklenemedi',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      await seoApi.updateSettings(settings);
      toast({
        title: 'Başarılı',
        description: 'SEO ayarları kaydedildi',
      });
    } catch (error) {
      console.error('SEO ayarları kaydetme hatası:', error);
      toast({
        title: 'Hata',
        description: 'SEO ayarları kaydedilemedi',
        variant: 'destructive',
      });
    } finally {
      setSaving(false);
    }
  };

  const handleChange = (field: keyof SEOSettings, value: string) => {
    setSettings((prev) => ({ ...prev, [field]: value }));
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">SEO Ayarları</h1>
            <p className="text-muted-foreground mt-2">
              Site genelinde geçerli SEO ayarlarını yönetin
            </p>
          </div>
          <Button onClick={handleSave} disabled={saving}>
            {saving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Kaydediliyor...
              </>
            ) : (
              <>
                <Save className="w-4 h-4 mr-2" />
                Kaydet
              </>
            )}
          </Button>
        </div>

        <Tabs defaultValue="general" className="space-y-6">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="general">
              <Globe className="w-4 h-4 mr-2" />
              Genel
            </TabsTrigger>
            <TabsTrigger value="social">
              <Image className="w-4 h-4 mr-2" />
              Sosyal Medya
            </TabsTrigger>
            <TabsTrigger value="analytics">
              <BarChart className="w-4 h-4 mr-2" />
              Analytics
            </TabsTrigger>
            <TabsTrigger value="robots">
              <Code className="w-4 h-4 mr-2" />
              Robots.txt
            </TabsTrigger>
          </TabsList>

          {/* Genel Ayarlar */}
          <TabsContent value="general">
            <Card>
              <CardHeader>
                <CardTitle>Genel SEO Ayarları</CardTitle>
                <CardDescription>
                  Site genelinde kullanılacak temel SEO bilgileri
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="site_name">Site Adı *</Label>
                  <Input
                    id="site_name"
                    value={settings.site_name || ''}
                    onChange={(e) => handleChange('site_name', e.target.value)}
                    placeholder="Trip Planner"
                  />
                  <p className="text-sm text-muted-foreground">
                    Tarayıcı sekmesinde ve arama sonuçlarında görünecek site adı
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="site_description">Site Açıklaması</Label>
                  <Textarea
                    id="site_description"
                    value={settings.site_description || ''}
                    onChange={(e) => handleChange('site_description', e.target.value)}
                    placeholder="Seyahatlerinizi planlayın, keşfedin ve unutulmaz anılar biriktirin..."
                    rows={4}
                  />
                  <p className="text-sm text-muted-foreground">
                    Arama motorlarında görünecek site açıklaması (150-160 karakter önerilir)
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="site_keywords">Anahtar Kelimeler</Label>
                  <Input
                    id="site_keywords"
                    value={settings.site_keywords || ''}
                    onChange={(e) => handleChange('site_keywords', e.target.value)}
                    placeholder="seyahat, tatil, gezi, planlama, tur"
                  />
                  <p className="text-sm text-muted-foreground">
                    Virgülle ayrılmış anahtar kelimeler
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="default_og_image">Varsayılan OG Görseli</Label>
                  <Input
                    id="default_og_image"
                    value={settings.default_og_image || ''}
                    onChange={(e) => handleChange('default_og_image', e.target.value)}
                    placeholder="https://example.com/og-image.jpg"
                  />
                  <p className="text-sm text-muted-foreground">
                    Sosyal medyada paylaşıldığında görünecek varsayılan görsel (1200x630 px önerilir)
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="favicon_url">Favicon URL</Label>
                  <Input
                    id="favicon_url"
                    value={settings.favicon_url || ''}
                    onChange={(e) => handleChange('favicon_url', e.target.value)}
                    placeholder="https://example.com/favicon.ico"
                  />
                  <p className="text-sm text-muted-foreground">
                    Tarayıcı sekmesinde görünecek favicon (32x32 px veya 16x16 px)
                  </p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Sosyal Medya Ayarları */}
          <TabsContent value="social">
            <Card>
              <CardHeader>
                <CardTitle>Sosyal Medya Entegrasyonu</CardTitle>
                <CardDescription>
                  Facebook, Twitter ve diğer sosyal medya platformları için ayarlar
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="facebook_app_id">Facebook App ID</Label>
                  <Input
                    id="facebook_app_id"
                    value={settings.facebook_app_id || ''}
                    onChange={(e) => handleChange('facebook_app_id', e.target.value)}
                    placeholder="123456789012345"
                  />
                  <p className="text-sm text-muted-foreground">
                    Facebook Open Graph için uygulama ID'si
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="twitter_handle">Twitter Kullanıcı Adı</Label>
                  <Input
                    id="twitter_handle"
                    value={settings.twitter_handle || ''}
                    onChange={(e) => handleChange('twitter_handle', e.target.value)}
                    placeholder="@tripplanner"
                  />
                  <p className="text-sm text-muted-foreground">
                    Twitter kartlarında görünecek kullanıcı adı (@ ile başlayın)
                  </p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Analytics Ayarları */}
          <TabsContent value="analytics">
            <Card>
              <CardHeader>
                <CardTitle>Analytics ve Doğrulama</CardTitle>
                <CardDescription>
                  Google Analytics ve Search Console entegrasyonu
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="google_analytics_id">Google Analytics ID</Label>
                  <Input
                    id="google_analytics_id"
                    value={settings.google_analytics_id || ''}
                    onChange={(e) => handleChange('google_analytics_id', e.target.value)}
                    placeholder="G-XXXXXXXXXX veya UA-XXXXXXXXX-X"
                  />
                  <p className="text-sm text-muted-foreground">
                    Google Analytics 4 (GA4) veya Universal Analytics ID'si
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="google_search_console_verification">
                    Google Search Console Doğrulama Kodu
                  </Label>
                  <Input
                    id="google_search_console_verification"
                    value={settings.google_search_console_verification || ''}
                    onChange={(e) =>
                      handleChange('google_search_console_verification', e.target.value)
                    }
                    placeholder="abcdefghijklmnopqrstuvwxyz123456"
                  />
                  <p className="text-sm text-muted-foreground">
                    Google Search Console meta tag doğrulama kodu (content değeri)
                  </p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Robots.txt */}
          <TabsContent value="robots">
            <Card>
              <CardHeader>
                <CardTitle>Robots.txt</CardTitle>
                <CardDescription>
                  Arama motoru botları için yönergeler
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="robots_txt">Robots.txt İçeriği</Label>
                  <Textarea
                    id="robots_txt"
                    value={settings.robots_txt || ''}
                    onChange={(e) => handleChange('robots_txt', e.target.value)}
                    placeholder="User-agent: *&#10;Allow: /"
                    rows={12}
                    className="font-mono text-sm"
                  />
                  <p className="text-sm text-muted-foreground">
                    Arama motoru botlarının hangi sayfalara erişebileceğini belirler
                  </p>
                </div>

                <div className="rounded-lg bg-muted p-4 space-y-2">
                  <p className="text-sm font-medium">Örnek Robots.txt:</p>
                  <pre className="text-xs font-mono bg-background p-3 rounded overflow-x-auto">
{`User-agent: *
Allow: /
Disallow: /admin/
Disallow: /api/
Disallow: /private/

Sitemap: ${window.location.origin}/sitemap.xml`}
                  </pre>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        <div className="flex justify-end">
          <Button onClick={handleSave} disabled={saving} size="lg">
            {saving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Kaydediliyor...
              </>
            ) : (
              <>
                <Save className="w-4 h-4 mr-2" />
                Tüm Ayarları Kaydet
              </>
            )}
          </Button>
        </div>
    </div>
  );
}
