import {
  CheckCircle2,
  DollarSign,
  History,
  Settings,
  TrendingUp,
  Users,
  Wallet,
  XCircle,
} from 'lucide-react';
import React, { 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,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { Switch } from '@/components/ui/switch';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { adminProvidersApi } from '@/db/api';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';
import { useQuery, useQueryClient } from '@tanstack/react-query';

interface ProviderStats {
  credit_balance: number;
  purchased_leads_count: number;
  total_spend: number;
}

interface Transaction {
  id: string;
  created_at: string;
  transaction_type: 'credit_purchase' | 'lead_purchase' | 'admin_credit' | 'admin_debit';
  amount: number;
  description: string;
  balance_after: number;
}

const AdminProvidersManagement: React.FC = () => {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const { profile: authProfile } = useAuth();
  const [loading, setLoading] = useState(true);
  const [providers, setProviders] = useState<any[]>([]);
  const [selectedProvider, setSelectedProvider] = useState<any>(null);
  
  // Dialog states
  const [showAdjustCreditsDialog, setShowAdjustCreditsDialog] = useState(false);
  const [showTransactionsDialog, setShowTransactionsDialog] = useState(false);
  
  // Forms
  const [adjustCreditsForm, setAdjustCreditsForm] = useState({
    amount: 0,
    type: 'credit' as 'credit' | 'debit',
    description: ''
  });

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

  const loadProviders = async () => {
    try {
      setLoading(true);
      const data = await adminProvidersApi.getAll();
      setProviders(data);
    } catch (error: any) {
      console.error('Error loading providers:', error);
      toast({
        title: 'Error',
        description: 'Failed to load providers.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleToggleStatus = async (provider: any) => {
    try {
      if (!authProfile) throw new Error('Not authenticated');

      await adminProvidersApi.toggleStatus(provider.id, !provider.is_active, authProfile.id);

      toast({
        title: 'Success',
        description: `Provider ${!provider.is_active ? 'activated' : 'deactivated'} successfully.`,
      });

      await loadProviders();
    } catch (error: any) {
      console.error('Error toggling provider status:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to update provider status.',
        variant: 'destructive',
      });
    }
  };

  // Provider Stats Query
  const { data: providerStats } = useQuery({
    queryKey: ['provider-stats', selectedProvider?.id],
    queryFn: async () => {
      if (!selectedProvider?.id) return null;
      return {
        credit_balance: selectedProvider.credit_balance || 0,
        purchased_leads_count: selectedProvider.purchased_leads_count || 0,
        total_spend: selectedProvider.total_spend || 0
      } as ProviderStats;
    },
    enabled: !!selectedProvider?.id
  });

  // Transactions Query
  const { data: transactions } = useQuery({
    queryKey: ['provider-transactions', selectedProvider?.id],
    queryFn: async () => {
      if (!selectedProvider?.id) return [];
      const { data, error } = await supabase
        .from('provider_wallet_transactions')
        .select('*')
        .eq('provider_id', selectedProvider.id)
        .order('created_at', { ascending: false });
      
      if (error) throw error;
      return data as Transaction[];
    },
    enabled: !!selectedProvider?.id && showTransactionsDialog
  });

  const handleAdjustCredits = async () => {
    try {
      const { error } = await  (supabase as any).rpc('admin_adjust_provider_credits', {
        p_provider_id: selectedProvider.id,
        p_amount: adjustCreditsForm.type === 'credit' 
          ? adjustCreditsForm.amount 
          : -adjustCreditsForm.amount,
        p_description: adjustCreditsForm.description
      });

      if (error) throw error;

      toast({
        title: 'Başarılı',
        description: 'Kredi bakiyesi güncellendi',
      });

      setShowAdjustCreditsDialog(false);
      queryClient.invalidateQueries({ queryKey: ['provider-stats', selectedProvider.id] });
      queryClient.invalidateQueries({ queryKey: ['provider-transactions', selectedProvider.id] });
      loadProviders(); // Reload table data
    } catch (error) {
      toast({
        title: 'Hata',
        description: 'Kredi bakiyesi güncellenirken hata oluştu',
        variant: 'destructive'
      });
    }
  };

  const getTransactionTypeBadge = (type: string) => {
    const badgeConfig: Record<string, { variant: "default" | "secondary" | "destructive" | "outline", label: string }> = {
      'credit_purchase': { variant: 'default', label: 'Kredi Satın Alma' },
      'lead_purchase': { variant: 'default', label: 'Lead Satın Alma' },
      'admin_credit': { variant: 'secondary', label: 'Admin Kredi' },
      'admin_debit': { variant: 'destructive', label: 'Admin Borç' }
    };
    
    const config = badgeConfig[type] || { variant: 'default', label: type };
    // @ts-ignore
    return <Badge variant={config.variant}>{config.label}</Badge>;
  };

  const formatAmount = (amount: number) => {
    const isPositive = amount > 0;
    return (
      <span className={isPositive ? 'text-green-600' : 'text-red-600'}>
        {isPositive ? '+' : ''}{amount} credits
      </span>
    );
  };

  // Calculate summary stats
  const totalProviders = providers.length;
  const activeProviders = providers.filter(p => p.is_active).length;
  const totalCreditsInSystem = providers.reduce((sum, p) => sum + (p.credit_balance || 0), 0);
  const totalSpent = providers.reduce((sum, p) => sum + (p.total_spend || 0), 0);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold">Providers Management</h1>
        <p className="text-muted-foreground mt-1">
          Manage provider accounts, credits, and status
        </p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Total Providers</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalProviders}</div>
            <p className="text-xs text-muted-foreground mt-1">
              {activeProviders} active
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Active Providers</CardTitle>
            <CheckCircle2 className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{activeProviders}</div>
            <p className="text-xs text-muted-foreground mt-1">
              {totalProviders > 0 ? ((activeProviders / totalProviders) * 100).toFixed(1) : 0}% of total
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Credits in System</CardTitle>
            <Wallet className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalCreditsInSystem}</div>
            <p className="text-xs text-muted-foreground mt-1">Total balance</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Total Spent</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{totalSpent}</div>
            <p className="text-xs text-muted-foreground mt-1">All time</p>
          </CardContent>
        </Card>
      </div>

      {/* Providers Table */}
      <Card>
        <CardHeader>
          <CardTitle>All Providers ({providers.length})</CardTitle>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="space-y-3">
              {[1, 2, 3, 4, 5].map((i) => (
                <Skeleton key={i} className="h-16 w-full bg-muted" />
              ))}
            </div>
          ) : providers.length === 0 ? (
            <div className="text-center py-12">
              <Users className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
              <p className="text-lg font-medium">No providers found</p>
              <p className="text-sm text-muted-foreground">
                Providers will appear here once they register
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Provider</TableHead>
                    <TableHead>Business Name</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Credit Balance</TableHead>
                    <TableHead>Purchased Leads</TableHead>
                    <TableHead>Total Spend</TableHead>
                    <TableHead>Joined</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {providers.map((provider) => (
                    <TableRow key={provider.id}>
                      <TableCell>
                        <div>
                          <p className="font-medium">{provider.full_name || provider.username}</p>
                          <p className="text-xs text-muted-foreground">{provider.email}</p>
                        </div>
                      </TableCell>
                      <TableCell>
                        <p className="font-medium">{provider.business_name || 'N/A'}</p>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Switch
                            checked={provider.is_active}
                            onCheckedChange={() => handleToggleStatus(provider)}
                          />
                          {provider.is_active ? (
                            <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                              <CheckCircle2 className="h-3 w-3 mr-1" />
                              Active
                            </Badge>
                          ) : (
                            <Badge variant="outline" className="bg-gray-50 text-gray-700 border-gray-200">
                              <XCircle className="h-3 w-3 mr-1" />
                              Inactive
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Wallet className="h-4 w-4 text-muted-foreground" />
                          <span className="font-semibold">{provider.credit_balance || 0}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <DollarSign className="h-4 w-4 text-muted-foreground" />
                          <span className="font-semibold">{provider.purchased_leads_count || 0}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <TrendingUp className="h-4 w-4 text-muted-foreground" />
                          <span className="font-semibold">{provider.total_spend || 0}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm">
                          {new Date(provider.created_at).toLocaleDateString()}
                        </span>
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => {
                              setSelectedProvider(provider);
                              setShowTransactionsDialog(true);
                            }}
                          >
                            <History className="h-4 w-4 mr-1" />
                            Geçmiş
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => {
                              setSelectedProvider(provider);
                              setShowAdjustCreditsDialog(true);
                            }}
                          >
                            <Settings className="h-4 w-4 mr-1" />
                            Kredi
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Transaction History Dialog */}
      <Dialog open={showTransactionsDialog} onOpenChange={setShowTransactionsDialog}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>İşlem Geçmişi - {selectedProvider?.business_name || selectedProvider?.username}</DialogTitle>
          </DialogHeader>
          
          <div className="grid grid-cols-3 gap-4 mb-6">
            <Card>
              <CardContent className="pt-6">
                <div className="text-2xl font-bold">{providerStats?.credit_balance || 0}</div>
                <p className="text-xs text-muted-foreground">Mevcut Kredi Bakiyesi</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6">
                <div className="text-2xl font-bold">{providerStats?.purchased_leads_count || 0}</div>
                <p className="text-xs text-muted-foreground">Satın Alınan Lead Sayısı</p>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="pt-6">
                <div className="text-2xl font-bold">{providerStats?.total_spend || 0}</div>
                <p className="text-xs text-muted-foreground">Toplam Harcama</p>
              </CardContent>
            </Card>
          </div>

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Tarih</TableHead>
                <TableHead>Tip</TableHead>
                <TableHead>Miktar</TableHead>
                <TableHead>Açıklama</TableHead>
                <TableHead>İşlem Sonrası Bakiye</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {transactions?.map((transaction) => (
                <TableRow key={transaction.id}>
                  <TableCell>
                    {new Date(transaction.created_at).toLocaleDateString('tr-TR', {
                      day: 'numeric',
                      month: 'short',
                      year: 'numeric',
                      hour: '2-digit',
                      minute: '2-digit'
                    })}
                  </TableCell>
                  <TableCell>{getTransactionTypeBadge(transaction.transaction_type)}</TableCell>
                  <TableCell>{formatAmount(transaction.amount)}</TableCell>
                  <TableCell>{transaction.description}</TableCell>
                  <TableCell>{transaction.balance_after} credits</TableCell>
                </TableRow>
              ))}
              {(!transactions || transactions.length === 0) && (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-4">İşlem bulunamadı</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </DialogContent>
      </Dialog>

      {/* Adjust Credits Dialog */}
      <Dialog open={showAdjustCreditsDialog} onOpenChange={setShowAdjustCreditsDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Kredi Ayarla - {selectedProvider?.business_name || selectedProvider?.username}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 pt-4">
            <div className="p-4 bg-muted rounded-lg">
              <p className="text-sm text-muted-foreground">Mevcut Bakiye</p>
              <p className="text-2xl font-bold">{selectedProvider?.credit_balance || 0} credits</p>
            </div>
            
            <div className="space-y-2">
              <Label>İşlem Tipi</Label>
              <Select
                value={adjustCreditsForm.type}
                onValueChange={(value) => 
                  setAdjustCreditsForm({ ...adjustCreditsForm, type: value as 'credit' | 'debit' })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="credit">Kredi Ekle</SelectItem>
                  <SelectItem value="debit">Kredi Çıkar</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>Miktar</Label>
              <Input
                type="number"
                value={adjustCreditsForm.amount}
                onChange={(e) => 
                  setAdjustCreditsForm({ ...adjustCreditsForm, amount: Number(e.target.value) })
                }
                placeholder="Kredi miktarı"
              />
            </div>

            <div className="space-y-2">
              <Label>Açıklama</Label>
              <Textarea
                value={adjustCreditsForm.description}
                onChange={(e) => 
                  setAdjustCreditsForm({ ...adjustCreditsForm, description: e.target.value })
                }
                placeholder="İşlem açıklaması"
              />
            </div>
          </div>
          <DialogFooter className="pt-4">
            <Button variant="outline" onClick={() => setShowAdjustCreditsDialog(false)}>
              İptal
            </Button>
            <Button onClick={handleAdjustCredits}>
              Onayla
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default AdminProvidersManagement;
