import { Clock, ExternalLink, Loader2, Search, Sparkles } from 'lucide-react';
import { useEffect, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { adminAdvancedApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';

interface SearchResult {
  query: string;
  response: string;
  sources: Array<{
    uri: string;
    title: string;
  }>;
  timestamp: Date;
}

export default function AdminAISearch() {
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<SearchResult[]>([]);
  const [currentStream, setCurrentStream] = useState('');
  const { toast } = useToast();

  const handleSearch = async () => {
    if (!query.trim()) {
      toast({
        title: 'Hata',
        description: 'Lütfen bir arama sorgusu girin',
        variant: 'destructive',
      });
      return;
    }

    setLoading(true);
    setCurrentStream('');

    try {
      // Call AI search with streaming
      const authHeader = (supabase as any).rest?.headers?.['Authorization'] || `Bearer ${import.meta.env.VITE_SUPABASE_ANON_KEY}`;
      
      const response = await fetch(
        `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/ai-search`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': authHeader,
          },
          body: JSON.stringify({ query }),
        }
      );

      if (!response.ok) {
        throw new Error('AI arama başarısız oldu');
      }

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let fullResponse = '';
      let sources: any[] = [];

      if (reader) {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const jsonData = JSON.parse(line.slice(6));
                
                if (jsonData.candidates?.[0]?.content?.parts?.[0]?.text) {
                  const text = jsonData.candidates[0].content.parts[0].text;
                  fullResponse += text;
                  setCurrentStream(fullResponse);
                }

                if (jsonData.candidates?.[0]?.groundingMetadata?.groundingChunks) {
                  sources = jsonData.candidates[0].groundingMetadata.groundingChunks;
                }
              } catch (e) {
                // Ignore parse errors for incomplete chunks
              }
            }
          }
        }
      }

      const newResult: SearchResult = {
        query,
        response: fullResponse,
        sources: sources.map((s: any) => ({
          uri: s.web?.uri || '',
          title: s.web?.title || '',
        })),
        timestamp: new Date(),
      };

      setResults([newResult, ...results]);
      setQuery('');
      setCurrentStream('');

    } catch (error: any) {
      console.error('AI Search error:', error);
      toast({
        title: 'Hata',
        description: error.message || 'AI arama sırasında bir hata oluştu',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold">AI Arama</h1>
        <p className="text-muted-foreground mt-2">
          Gemini AI ile güçlendirilmiş akıllı arama sistemi
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-primary" />
            Yeni Arama
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex gap-2">
            <Input
              placeholder="Sorunuzu yazın..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && !loading && handleSearch()}
              disabled={loading}
              className="flex-1"
            />
            <Button onClick={handleSearch} disabled={loading || !query.trim()}>
              {loading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Aranıyor...
                </>
              ) : (
                <>
                  <Search className="mr-2 h-4 w-4" />
                  Ara
                </>
              )}
            </Button>
          </div>
        </CardContent>
      </Card>

      {currentStream && (
        <Card className="border-primary">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Loader2 className="h-5 w-5 animate-spin text-primary" />
              Yanıt Oluşturuluyor...
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="prose prose-sm max-w-none dark:prose-invert">
              <ReactMarkdown>{currentStream}</ReactMarkdown>
            </div>
          </CardContent>
        </Card>
      )}

      <div className="space-y-4">
        {results.map((result, index) => (
          <Card key={index}>
            <CardHeader>
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <CardTitle className="text-lg">{result.query}</CardTitle>
                  <div className="flex items-center gap-2 mt-2 text-sm text-muted-foreground">
                    <Clock className="h-4 w-4" />
                    {result.timestamp.toLocaleString('tr-TR')}
                  </div>
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="prose prose-sm max-w-none dark:prose-invert">
                <ReactMarkdown>{result.response}</ReactMarkdown>
              </div>

              {result.sources.length > 0 && (
                <>
                  <Separator />
                  <div>
                    <h4 className="text-sm font-semibold mb-2">Kaynaklar:</h4>
                    <div className="space-y-2">
                      {result.sources.map((source, idx) => (
                        <a
                          key={idx}
                          href={source.uri}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center gap-2 text-sm text-primary hover:underline"
                        >
                          <ExternalLink className="h-3 w-3" />
                          {source.title}
                        </a>
                      ))}
                    </div>
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        ))}
      </div>

      {results.length === 0 && !loading && !currentStream && (
        <Card>
          <CardContent className="py-12 text-center">
            <Sparkles className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">
              AI arama yapmak için yukarıdaki arama kutusunu kullanın
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
