import {
  Eye,
  EyeOff,
  FileText,
  Loader2,
  Pencil,
  Plus,
  Search,
  Trash2,
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import { seoApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';
import type { PageSEO } from '@/types/seo';

export default function PageSEOManagement() {
  const [pages, setPages] = useState<PageSEO[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingPage, setEditingPage] = useState<PageSEO | null>(null);
  const { toast } = useToast();

  const [formData, setFormData] = useState<Partial<PageSEO>>({
    page_path: '',
    page_title: '',
    meta_description: '',
    meta_keywords: '',
    og_title: '',
    og_description: '',
    og_image: '',
    og_type: 'website',
    twitter_card: 'summary_large_image',
    twitter_title: '',
    twitter_description: '',
    twitter_image: '',
    canonical_url: '',
    noindex: false,
    nofollow: false,
  });

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

  const loadPages = async () => {
    try {
      setLoading(true);
      const data = await seoApi.getAllPageSEO();
      setPages(data);
    } catch (error) {
      console.error('Sayfa SEO bilgileri yükleme hatası:', error);
      toast({
        title: 'Hata',
        description: 'Sayfa SEO bilgileri yüklenemedi',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleOpenDialog = (page?: PageSEO) => {
    if (page) {
      setEditingPage(page);
      setFormData(page);
    } else {
      setEditingPage(null);
      setFormData({
        page_path: '',
        page_title: '',
        meta_description: '',
        meta_keywords: '',
        og_title: '',
        og_description: '',
        og_image: '',
        og_type: 'website',
        twitter_card: 'summary_large_image',
        twitter_title: '',
        twitter_description: '',
        twitter_image: '',
        canonical_url: '',
        noindex: false,
        nofollow: false,
      });
    }
    setDialogOpen(true);
  };

  const handleSave = async () => {
    try {
      if (!formData.page_path || !formData.page_title) {
        toast({
          title: 'Hata',
          description: 'Sayfa yolu ve başlık zorunludur',
          variant: 'destructive',
        });
        return;
      }

      if (editingPage) {
        await seoApi.updatePageSEO(editingPage.id, formData);
        toast({
          title: 'Başarılı',
          description: 'Sayfa SEO bilgileri güncellendi',
        });
      } else {
        await seoApi.createPageSEO(formData as Omit<PageSEO, 'id' | 'created_at' | 'updated_at'>);
        toast({
          title: 'Başarılı',
          description: 'Sayfa SEO bilgileri oluşturuldu',
        });
      }

      setDialogOpen(false);
      loadPages();
    } catch (error: any) {
      console.error('Sayfa SEO kaydetme hatası:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Sayfa SEO bilgileri kaydedilemedi',
        variant: 'destructive',
      });
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Bu sayfa SEO bilgilerini silmek istediğinizden emin misiniz?')) {
      return;
    }

    try {
      await seoApi.deletePageSEO(id);
      toast({
        title: 'Başarılı',
        description: 'Sayfa SEO bilgileri silindi',
      });
      loadPages();
    } catch (error) {
      console.error('Sayfa SEO silme hatası:', error);
      toast({
        title: 'Hata',
        description: 'Sayfa SEO bilgileri silinemedi',
        variant: 'destructive',
      });
    }
  };

  const filteredPages = pages.filter(
    (page) =>
      page.page_path.toLowerCase().includes(searchQuery.toLowerCase()) ||
      page.page_title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">Sayfa SEO Yönetimi</h1>
            <p className="text-muted-foreground mt-2">
              Her sayfa için özel SEO ayarları yapın
            </p>
          </div>
          <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
            <DialogTrigger asChild>
              <Button onClick={() => handleOpenDialog()}>
                <Plus className="w-4 h-4 mr-2" />
                Yeni Sayfa SEO
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle>
                  {editingPage ? 'Sayfa SEO Düzenle' : 'Yeni Sayfa SEO'}
                </DialogTitle>
                <DialogDescription>
                  Sayfa için SEO meta bilgilerini girin
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-6 py-4">
                {/* Temel Bilgiler */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">Temel Bilgiler</h3>
                  
                  <div className="space-y-2">
                    <Label htmlFor="page_path">Sayfa Yolu *</Label>
                    <Input
                      id="page_path"
                      value={formData.page_path || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, page_path: e.target.value })
                      }
                      placeholder="/about, /trips, /contact"
                      disabled={!!editingPage}
                    />
                    <p className="text-xs text-muted-foreground">
                      Örnek: /about, /trips, /contact (/ ile başlamalı)
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="page_title">Sayfa Başlığı *</Label>
                    <Input
                      id="page_title"
                      value={formData.page_title || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, page_title: e.target.value })
                      }
                      placeholder="Hakkımızda | Trip Planner"
                    />
                    <p className="text-xs text-muted-foreground">
                      50-60 karakter önerilir
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="meta_description">Meta Açıklama</Label>
                    <Textarea
                      id="meta_description"
                      value={formData.meta_description || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, meta_description: e.target.value })
                      }
                      placeholder="Sayfa açıklaması..."
                      rows={3}
                    />
                    <p className="text-xs text-muted-foreground">
                      150-160 karakter önerilir
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="meta_keywords">Anahtar Kelimeler</Label>
                    <Input
                      id="meta_keywords"
                      value={formData.meta_keywords || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, meta_keywords: e.target.value })
                      }
                      placeholder="kelime1, kelime2, kelime3"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="canonical_url">Canonical URL</Label>
                    <Input
                      id="canonical_url"
                      value={formData.canonical_url || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, canonical_url: e.target.value })
                      }
                      placeholder="https://example.com/page"
                    />
                  </div>
                </div>

                {/* Open Graph */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">Open Graph (Facebook)</h3>
                  
                  <div className="space-y-2">
                    <Label htmlFor="og_title">OG Başlık</Label>
                    <Input
                      id="og_title"
                      value={formData.og_title || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, og_title: e.target.value })
                      }
                      placeholder="Boş bırakılırsa sayfa başlığı kullanılır"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="og_description">OG Açıklama</Label>
                    <Textarea
                      id="og_description"
                      value={formData.og_description || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, og_description: e.target.value })
                      }
                      placeholder="Boş bırakılırsa meta açıklama kullanılır"
                      rows={2}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="og_image">OG Görsel URL</Label>
                    <Input
                      id="og_image"
                      value={formData.og_image || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, og_image: e.target.value })
                      }
                      placeholder="https://example.com/image.jpg"
                    />
                    <p className="text-xs text-muted-foreground">
                      1200x630 px önerilir
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="og_type">OG Tipi</Label>
                    <Select
                      value={formData.og_type || 'website'}
                      onValueChange={(value) =>
                        setFormData({ ...formData, og_type: value })
                      }
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="website">Website</SelectItem>
                        <SelectItem value="article">Article</SelectItem>
                        <SelectItem value="product">Product</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* Twitter Card */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">Twitter Card</h3>
                  
                  <div className="space-y-2">
                    <Label htmlFor="twitter_card">Twitter Card Tipi</Label>
                    <Select
                      value={formData.twitter_card || 'summary_large_image'}
                      onValueChange={(value) =>
                        setFormData({ ...formData, twitter_card: value })
                      }
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="summary">Summary</SelectItem>
                        <SelectItem value="summary_large_image">
                          Summary Large Image
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="twitter_title">Twitter Başlık</Label>
                    <Input
                      id="twitter_title"
                      value={formData.twitter_title || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, twitter_title: e.target.value })
                      }
                      placeholder="Boş bırakılırsa OG başlık kullanılır"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="twitter_description">Twitter Açıklama</Label>
                    <Textarea
                      id="twitter_description"
                      value={formData.twitter_description || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, twitter_description: e.target.value })
                      }
                      placeholder="Boş bırakılırsa OG açıklama kullanılır"
                      rows={2}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="twitter_image">Twitter Görsel URL</Label>
                    <Input
                      id="twitter_image"
                      value={formData.twitter_image || ''}
                      onChange={(e) =>
                        setFormData({ ...formData, twitter_image: e.target.value })
                      }
                      placeholder="Boş bırakılırsa OG görsel kullanılır"
                    />
                  </div>
                </div>

                {/* Robots */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">Arama Motoru Ayarları</h3>
                  
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="noindex"
                      checked={formData.noindex || false}
                      onCheckedChange={(checked) =>
                        setFormData({ ...formData, noindex: checked as boolean })
                      }
                    />
                    <Label htmlFor="noindex" className="cursor-pointer">
                      Noindex (Arama motorlarında gösterme)
                    </Label>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="nofollow"
                      checked={formData.nofollow || false}
                      onCheckedChange={(checked) =>
                        setFormData({ ...formData, nofollow: checked as boolean })
                      }
                    />
                    <Label htmlFor="nofollow" className="cursor-pointer">
                      Nofollow (Linkleri takip etme)
                    </Label>
                  </div>
                </div>
              </div>

              <DialogFooter>
                <Button variant="outline" onClick={() => setDialogOpen(false)}>
                  İptal
                </Button>
                <Button onClick={handleSave}>
                  {editingPage ? 'Güncelle' : 'Oluştur'}
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>

        {/* Arama */}
        <div className="flex items-center gap-4">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="Sayfa yolu veya başlık ara..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
            />
          </div>
        </div>

        {/* Tablo */}
        <Card>
          <CardHeader>
            <CardTitle>Sayfa SEO Listesi</CardTitle>
            <CardDescription>
              Toplam {filteredPages.length} sayfa
            </CardDescription>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="flex items-center justify-center h-64">
                <Loader2 className="w-8 h-8 animate-spin text-primary" />
              </div>
            ) : filteredPages.length === 0 ? (
              <div className="text-center py-12">
                <FileText className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
                <p className="text-muted-foreground">
                  {searchQuery
                    ? 'Arama sonucu bulunamadı'
                    : 'Henüz sayfa SEO bilgisi eklenmemiş'}
                </p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Sayfa Yolu</TableHead>
                      <TableHead>Başlık</TableHead>
                      <TableHead>Durum</TableHead>
                      <TableHead className="text-right">İşlemler</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredPages.map((page) => (
                      <TableRow key={page.id}>
                        <TableCell className="font-mono text-sm">
                          {page.page_path}
                        </TableCell>
                        <TableCell>{page.page_title}</TableCell>
                        <TableCell>
                          <div className="flex gap-2">
                            {page.noindex && (
                              <Badge variant="secondary">
                                <EyeOff className="w-3 h-3 mr-1" />
                                Noindex
                              </Badge>
                            )}
                            {page.nofollow && (
                              <Badge variant="secondary">Nofollow</Badge>
                            )}
                            {!page.noindex && !page.nofollow && (
                              <Badge variant="default">
                                <Eye className="w-3 h-3 mr-1" />
                                Aktif
                              </Badge>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleOpenDialog(page)}
                            >
                              <Pencil className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDelete(page.id)}
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
    </div>
  );
}
