import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/db/supabase';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { CheckCircle2, XCircle, AlertCircle, RefreshCw } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

interface Profile {
  id: string;
  email: string;
  username: string;
  full_name?: string;
  role: string;
  clerk_user_id?: string;
  created_at: string;
}

interface SiteSetting {
  id: string;
  key: string;
  value: string;
  created_at: string;
  updated_at: string;
}

export default function ClerkDiagnostics() {
  const { toast } = useToast();
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Check Clerk configuration
  const { data: clerkConfig, refetch: refetchConfig } = useQuery<SiteSetting | null>({
    queryKey: ['clerk-config'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('site_settings')
        .select('*')
        .eq('key', 'clerk_publishable_key')
        .maybeSingle();

      if (error) throw error;
      return data as SiteSetting | null;
    }
  });

  // Check profiles with Clerk ID
  const { data: clerkProfiles, refetch: refetchProfiles } = useQuery({
    queryKey: ['clerk-profiles'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('profiles')
        .select('id, email, username, full_name, role, clerk_user_id, created_at')
        .not('clerk_user_id', 'is', null)
        .order('created_at', { ascending: false });

      if (error) throw error;
      return data as Profile[];
    }
  });

  // Check profiles without Clerk ID
  const { data: nonClerkProfiles, refetch: refetchNonClerk } = useQuery<Profile[]>({
    queryKey: ['non-clerk-profiles'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('profiles')
        .select('id, email, username, full_name, role, created_at')
        .is('clerk_user_id', null)
        .order('created_at', { ascending: false });

      if (error) throw error;
      return data as Profile[];
    }
  });

  // Check recent profiles (last 24 hours)
  const { data: recentProfiles, refetch: refetchRecent } = useQuery<Profile[]>({
    queryKey: ['recent-profiles'],
    queryFn: async () => {
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);

      const { data, error } = await supabase
        .from('profiles')
        .select('id, email, username, role, clerk_user_id, created_at')
        .gte('created_at', yesterday.toISOString())
        .order('created_at', { ascending: false });

      if (error) throw error;
      return data as Profile[];
    }
  });

  const handleRefreshAll = async () => {
    setIsRefreshing(true);
    try {
      await Promise.all([
        refetchConfig(),
        refetchProfiles(),
        refetchNonClerk(),
        refetchRecent()
      ]);
      toast({
        title: 'Başarılı',
        description: 'Tüm veriler yenilendi'
      });
    } catch (error) {
      toast({
        title: 'Hata',
        description: 'Veriler yenilenirken bir hata oluştu',
        variant: 'destructive'
      });
    } finally {
      setIsRefreshing(false);
    }
  };

  const isClerkConfigured = clerkConfig?.value && clerkConfig.value.length > 10;

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Clerk Diagnostics</h1>
          <p className="text-muted-foreground mt-2">
            Clerk entegrasyonu ve kullanıcı senkronizasyonu durumu
          </p>
        </div>
        <Button onClick={handleRefreshAll} disabled={isRefreshing}>
          <RefreshCw className={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />
          Yenile
        </Button>
      </div>

      {/* Clerk Configuration Status */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            {isClerkConfigured ? (
              <CheckCircle2 className="h-5 w-5 text-green-500" />
            ) : (
              <XCircle className="h-5 w-5 text-red-500" />
            )}
            Clerk Yapılandırması
          </CardTitle>
          <CardDescription>
            Clerk API anahtarı durumu
          </CardDescription>
        </CardHeader>
        <CardContent>
          {isClerkConfigured ? (
            <div className="space-y-2">
              <Badge className="bg-green-100 text-green-700">✅ Aktif</Badge>
              <p className="text-sm text-muted-foreground">
                Clerk publishable key yapılandırılmış
              </p>
              <p className="text-xs font-mono bg-muted p-2 rounded">
                {clerkConfig.value.substring(0, 20)}...
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              <Badge className="bg-red-100 text-red-700">❌ Yapılandırılmamış</Badge>
              <p className="text-sm text-muted-foreground">
                Clerk publishable key bulunamadı
              </p>
              <Button variant="outline" size="sm" onClick={() => window.location.href = '/admin/settings'}>
                Ayarlara Git
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Statistics */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Clerk Kullanıcıları</CardTitle>
            <CardDescription>Clerk ID'si olan profiller</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold">{clerkProfiles?.length || 0}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Diğer Kullanıcılar</CardTitle>
            <CardDescription>Clerk ID'si olmayan profiller</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold">{nonClerkProfiles?.length || 0}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Son 24 Saat</CardTitle>
            <CardDescription>Yeni oluşturulan profiller</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold">{recentProfiles?.length || 0}</div>
          </CardContent>
        </Card>
      </div>

      {/* Recent Profiles */}
      <Card>
        <CardHeader>
          <CardTitle>Son Oluşturulan Profiller (24 saat)</CardTitle>
          <CardDescription>
            Yeni kullanıcı kayıtları ve profil oluşturma durumu
          </CardDescription>
        </CardHeader>
        <CardContent>
          {recentProfiles && recentProfiles.length > 0 ? (
            <div className="space-y-2">
              {recentProfiles.map((profile) => (
                <div key={profile.id} className="flex items-center justify-between p-3 border rounded-lg">
                  <div className="flex items-center gap-3">
                    {profile.clerk_user_id ? (
                      <CheckCircle2 className="h-5 w-5 text-green-500" />
                    ) : (
                      <AlertCircle className="h-5 w-5 text-yellow-500" />
                    )}
                    <div>
                      <p className="font-medium">{profile.email}</p>
                      <p className="text-sm text-muted-foreground">
                        {profile.username} • {profile.role}
                      </p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm text-muted-foreground">
                      {new Date(profile.created_at).toLocaleString('tr-TR')}
                    </p>
                    {profile.clerk_user_id ? (
                      <Badge className="bg-green-100 text-green-700 text-xs">Clerk</Badge>
                    ) : (
                      <Badge className="bg-yellow-100 text-yellow-700 text-xs">Diğer</Badge>
                    )}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              Son 24 saatte yeni profil oluşturulmamış
            </div>
          )}
        </CardContent>
      </Card>

      {/* Clerk Profiles */}
      <Card>
        <CardHeader>
          <CardTitle>Clerk Kullanıcıları</CardTitle>
          <CardDescription>
            Clerk ID'si olan tüm profiller
          </CardDescription>
        </CardHeader>
        <CardContent>
          {clerkProfiles && clerkProfiles.length > 0 ? (
            <div className="space-y-2">
              {clerkProfiles.map((profile) => (
                <div key={profile.id} className="flex items-center justify-between p-3 border rounded-lg">
                  <div>
                    <p className="font-medium">{profile.email}</p>
                    <p className="text-sm text-muted-foreground">
                      {profile.username} • {profile.role}
                    </p>
                    <p className="text-xs font-mono text-muted-foreground mt-1">
                      Clerk ID: {profile.clerk_user_id?.substring(0, 20)}...
                    </p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm text-muted-foreground">
                      {new Date(profile.created_at).toLocaleString('tr-TR')}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              Henüz Clerk kullanıcısı yok
            </div>
          )}
        </CardContent>
      </Card>

      {/* Non-Clerk Profiles */}
      <Card>
        <CardHeader>
          <CardTitle>Diğer Kullanıcılar</CardTitle>
          <CardDescription>
            Clerk ID'si olmayan profiller (demo login, manuel oluşturma vb.)
          </CardDescription>
        </CardHeader>
        <CardContent>
          {nonClerkProfiles && nonClerkProfiles.length > 0 ? (
            <div className="space-y-2">
              {nonClerkProfiles.map((profile) => (
                <div key={profile.id} className="flex items-center justify-between p-3 border rounded-lg">
                  <div>
                    <p className="font-medium">{profile.email}</p>
                    <p className="text-sm text-muted-foreground">
                      {profile.username} • {profile.role}
                    </p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm text-muted-foreground">
                      {new Date(profile.created_at).toLocaleString('tr-TR')}
                    </p>
                    <Badge className="bg-gray-100 text-gray-700 text-xs">Manuel</Badge>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              Tüm kullanıcılar Clerk ile oluşturulmuş
            </div>
          )}
        </CardContent>
      </Card>

      {/* Troubleshooting Tips */}
      <Card>
        <CardHeader>
          <CardTitle>Sorun Giderme İpuçları</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <h4 className="font-semibold mb-2">✅ Clerk yapılandırılmış ama kullanıcı yok?</h4>
            <p className="text-sm text-muted-foreground">
              1. Kullanıcıların en az bir kez giriş yapması gerekir<br />
              2. Webhook yapılandırması kontrol edilmeli<br />
              3. Browser console'da hata mesajları kontrol edilmeli
            </p>
          </div>

          <div>
            <h4 className="font-semibold mb-2">⚠️ Webhook nasıl yapılandırılır?</h4>
            <p className="text-sm text-muted-foreground">
              1. Clerk Dashboard → Webhooks<br />
              2. Endpoint: https://pkycoiknpdwzkarqelai.supabase.co/functions/v1/clerk-webhook<br />
              3. Events: user.created, user.updated, user.deleted<br />
              4. Secret'i Supabase Edge Functions Secrets'e ekleyin
            </p>
          </div>

          <div>
            <h4 className="font-semibold mb-2">🔍 Detaylı dokümantasyon</h4>
            <p className="text-sm text-muted-foreground">
              Proje kök dizininde CLERK_TROUBLESHOOTING.md dosyasına bakın
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
