import { Download, Edit, Image as ImageIcon, Loader2, Sparkles, Trash2, Upload } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import { adminAdvancedApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';

interface AdminImage {
  id: string;
  title: string;
  description: string | null;
  file_path: string;
  file_size: number | null;
  mime_type: string | null;
  width: number | null;
  height: number | null;
  generation_method: 'upload' | 'ai_generated';
  generation_prompt: string | null;
  tags: string[];
  created_at: string;
  profiles?: {
    email: string;
    full_name: string | null;
  };
}

export default function AdminImages() {
  const [images, setImages] = useState<AdminImage[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState('');
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [filter, setFilter] = useState<'all' | 'upload' | 'ai_generated'>('all');
  const { toast } = useToast();

  useEffect(() => {
    loadImages();
  }, [page, filter]);

  const loadImages = async () => {
    try {
      setLoading(true);
      const filters = filter !== 'all' ? { generation_method: filter } : undefined;
      const result = await adminAdvancedApi.getImages(page, 20, filters);
      setImages(result.images);
      setTotalPages(result.totalPages);
    } catch (error: any) {
      console.error('Error loading images:', error);
      toast({
        title: 'Hata',
        description: 'Görseller yüklenirken bir hata oluştu',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleUpload = async (file: File) => {
    try {
      setUploading(true);

      // Upload to Supabase Storage
      const fileExt = file.name.split('.').pop();
      const fileName = `${Date.now()}_${Math.random().toString(36).substring(7)}.${fileExt}`;
      const filePath = `admin-images/${fileName}`;

      const { error: uploadError } = await supabase.storage
        .from('images')
        .upload(filePath, file);

      if (uploadError) throw uploadError;

      // Get public URL
      const { data: { publicUrl } } = supabase.storage
        .from('images')
        .getPublicUrl(filePath);

      // Save to database
      await adminAdvancedApi.saveImage({
        title: file.name,
        file_path: publicUrl,
        file_size: file.size,
        mime_type: file.type,
        generation_method: 'upload',
      });

      toast({
        title: 'Başarılı',
        description: 'Görsel başarıyla yüklendi',
      });

      loadImages();
    } catch (error: any) {
      console.error('Upload error:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Görsel yüklenirken bir hata oluştu',
        variant: 'destructive',
      });
    } finally {
      setUploading(false);
    }
  };

  const handleGenerate = async (prompt: string) => {
    try {
      setGenerating(true);
      setGenerationProgress('Görsel oluşturuluyor...');

      // Submit generation task
      const submitResult = await adminAdvancedApi.generateImage([
        {
          parts: [{ text: prompt }]
        }
      ]);

      if (submitResult.status !== 0 || !submitResult.data?.taskId) {
        throw new Error('Görsel oluşturma görevi başlatılamadı');
      }

      const taskId = submitResult.data.taskId;
      setGenerationProgress('Görsel işleniyor... (Bu işlem birkaç dakika sürebilir)');

      // Poll for task completion
      let attempts = 0;
      const maxAttempts = 60; // 10 minutes with 10 second intervals

      while (attempts < maxAttempts) {
        await new Promise(resolve => setTimeout(resolve, 10000)); // Wait 10 seconds
        attempts++;

        const taskResult = await adminAdvancedApi.queryImageTask(taskId);

        if (taskResult.status !== 0) {
          throw new Error('Görsel durumu sorgulanamadı');
        }

        const taskStatus = taskResult.data.status;

        if (taskStatus === 'SUCCESS') {
          // Extract image from result
          const imageText = taskResult.data.result?.candidates?.[0]?.content?.parts?.[0]?.text;
          if (!imageText) {
            throw new Error('Görsel bulunamadı');
          }

          // Extract base64 from markdown format
          const base64Match = imageText.match(/data:image\/[^;]+;base64,([^)]+)/);
          if (!base64Match) {
            throw new Error('Görsel formatı geçersiz');
          }

          const base64Data = base64Match[1];
          const mimeType = imageText.match(/data:(image\/[^;]+);/)?.[1] || 'image/jpeg';

          // Convert base64 to blob
          const byteCharacters = atob(base64Data);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);
          const blob = new Blob([byteArray], { type: mimeType });

          // Upload to Supabase Storage
          const fileName = `${Date.now()}_generated.${mimeType.split('/')[1]}`;
          const filePath = `admin-images/${fileName}`;

          const { error: uploadError } = await supabase.storage
            .from('images')
            .upload(filePath, blob);

          if (uploadError) throw uploadError;

          // Get public URL
          const { data: { publicUrl } } = supabase.storage
            .from('images')
            .getPublicUrl(filePath);

          // Save to database
          await adminAdvancedApi.saveImage({
            title: `AI Generated: ${prompt.substring(0, 50)}`,
            description: prompt,
            file_path: publicUrl,
            file_size: blob.size,
            mime_type: mimeType,
            generation_method: 'ai_generated',
            generation_prompt: prompt,
          });

          toast({
            title: 'Başarılı',
            description: 'Görsel başarıyla oluşturuldu',
          });

          loadImages();
          return;

        } else if (taskStatus === 'FAILED' || taskStatus === 'TIMEOUT') {
          throw new Error(`Görsel oluşturma başarısız: ${taskStatus}`);
        }

        setGenerationProgress(`İşleniyor... (${attempts}/${maxAttempts})`);
      }

      throw new Error('Görsel oluşturma zaman aşımına uğradı');

    } catch (error: any) {
      console.error('Generation error:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Görsel oluşturulurken bir hata oluştu',
        variant: 'destructive',
      });
    } finally {
      setGenerating(false);
      setGenerationProgress('');
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Bu görseli silmek istediğinizden emin misiniz?')) return;

    try {
      await adminAdvancedApi.deleteImage(id);
      toast({
        title: 'Başarılı',
        description: 'Görsel başarıyla silindi',
      });
      loadImages();
    } catch (error: any) {
      console.error('Delete error:', error);
      toast({
        title: 'Hata',
        description: 'Görsel silinirken bir hata oluştu',
        variant: 'destructive',
      });
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Görsel Yönetimi</h1>
          <p className="text-muted-foreground mt-2">
            Görselleri yükleyin veya AI ile oluşturun
          </p>
        </div>

        <div className="flex gap-2">
          <Dialog>
            <DialogTrigger asChild>
              <Button variant="outline">
                <Upload className="mr-2 h-4 w-4" />
                Yükle
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Görsel Yükle</DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="file-upload">Dosya Seç</Label>
                  <Input
                    id="file-upload"
                    type="file"
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (file) handleUpload(file);
                    }}
                    disabled={uploading}
                  />
                </div>
                {uploading && (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Yükleniyor...
                  </div>
                )}
              </div>
            </DialogContent>
          </Dialog>

          <GenerateImageDialog onGenerate={handleGenerate} generating={generating} progress={generationProgress} />
        </div>
      </div>

      <Tabs value={filter} onValueChange={(v) => setFilter(v as any)}>
        <TabsList>
          <TabsTrigger value="all">Tümü</TabsTrigger>
          <TabsTrigger value="upload">Yüklenenler</TabsTrigger>
          <TabsTrigger value="ai_generated">AI Oluşturulan</TabsTrigger>
        </TabsList>
      </Tabs>

      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {[...Array(6)].map((_, i) => (
            <Card key={i}>
              <CardContent className="p-4">
                <Skeleton className="w-full h-48 mb-4" />
                <Skeleton className="h-4 w-3/4 mb-2" />
                <Skeleton className="h-3 w-1/2" />
              </CardContent>
            </Card>
          ))}
        </div>
      ) : images.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center">
            <ImageIcon className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">Henüz görsel yok</p>
          </CardContent>
        </Card>
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {images.map((image) => (
              <Card key={image.id}>
                <CardContent className="p-4">
                  <div className="relative group">
                    <img
                      src={image.file_path}
                      alt={image.title}
                      className="w-full h-48 object-cover rounded-md mb-4"
                    />
                    <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-2">
                      <Button
                        size="sm"
                        variant="destructive"
                        onClick={() => handleDelete(image.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  <h3 className="font-semibold truncate">{image.title}</h3>
                  {image.description && (
                    <p className="text-sm text-muted-foreground line-clamp-2 mt-1">
                      {image.description}
                    </p>
                  )}
                  <div className="flex items-center gap-2 mt-2">
                    <Badge variant={image.generation_method === 'ai_generated' ? 'default' : 'secondary'}>
                      {image.generation_method === 'ai_generated' ? (
                        <>
                          <Sparkles className="h-3 w-3 mr-1" />
                          AI
                        </>
                      ) : (
                        <>
                          <Upload className="h-3 w-3 mr-1" />
                          Yüklendi
                        </>
                      )}
                    </Badge>
                    {image.file_size && (
                      <span className="text-xs text-muted-foreground">
                        {(image.file_size / 1024).toFixed(0)} KB
                      </span>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {totalPages > 1 && (
            <div className="flex justify-center gap-2">
              <Button
                variant="outline"
                onClick={() => setPage(p => Math.max(1, p - 1))}
                disabled={page === 1}
              >
                Önceki
              </Button>
              <span className="flex items-center px-4">
                Sayfa {page} / {totalPages}
              </span>
              <Button
                variant="outline"
                onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
              >
                Sonraki
              </Button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

function GenerateImageDialog({ onGenerate, generating, progress }: { onGenerate: (prompt: string) => void; generating: boolean; progress: string }) {
  const [prompt, setPrompt] = useState('');
  const [open, setOpen] = useState(false);

  const handleSubmit = () => {
    if (prompt.trim()) {
      onGenerate(prompt);
      setPrompt('');
      setOpen(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button disabled={generating}>
          {generating ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              {progress || 'Oluşturuluyor...'}
            </>
          ) : (
            <>
              <Sparkles className="mr-2 h-4 w-4" />
              AI ile Oluştur
            </>
          )}
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>AI ile Görsel Oluştur</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <div>
            <Label htmlFor="prompt">Görsel Açıklaması</Label>
            <Textarea
              id="prompt"
              placeholder="Oluşturmak istediğiniz görseli detaylı olarak açıklayın..."
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              rows={4}
            />
          </div>
          <Button onClick={handleSubmit} disabled={!prompt.trim() || generating} className="w-full">
            <Sparkles className="mr-2 h-4 w-4" />
            Oluştur
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
