import { Plus, Users, Wallet } 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,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';

const AdminProviders = () => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [providers, setProviders] = useState<any[]>([]);
  const [selectedProvider, setSelectedProvider] = useState<any>(null);
  const [isAddCreditsOpen, setIsAddCreditsOpen] = useState(false);
  const [creditAmount, setCreditAmount] = useState('');
  const [isAdding, setIsAdding] = useState(false);

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

  const loadProviders = async () => {
    try {
      setLoading(true);

      // Get all providers
      const { data: profiles, error: profilesError } = await supabase
        .from('profiles')
        .select('*')
        .eq('role', 'provider');

      if (profilesError) throw profilesError;

      // Get provider services and wallets
      const providersWithData = await Promise.all(
        (profiles || []).map(async (profile: any) => {
          const { data: service } = await supabase
            .from('provider_services')
            .select('*')
            .eq('provider_id', profile.id)
            .maybeSingle();

          const { data: wallet } = await supabase
            .from('provider_wallets')
            .select('*')
            .eq('provider_id', profile.id)
            .maybeSingle();

          return {
            ...profile,
            service,
            wallet,
          };
        })
      );

      setProviders(providersWithData);
    } catch (error: any) {
      console.error('Error loading providers:', error);
      toast({
        title: 'Error',
        description: 'Failed to load providers.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleAddCredits = async () => {
    if (!selectedProvider || !creditAmount) return;

    const amount = parseInt(creditAmount);
    if (isNaN(amount) || amount <= 0) {
      toast({
        title: 'Invalid Amount',
        description: 'Please enter a valid credit amount.',
        variant: 'destructive',
      });
      return;
    }

    try {
      setIsAdding(true);

      await (supabase.rpc as any)('admin_adjust_credits', {
        p_provider_id: selectedProvider.id,
        p_amount: amount,
        p_reason: 'Admin kredi eklemesi',
      });

      toast({
        title: 'Credits Added',
        description: `Successfully added ${amount} credits to ${selectedProvider.email}.`,
      });

      setIsAddCreditsOpen(false);
      setCreditAmount('');
      setSelectedProvider(null);
      await loadProviders();
    } catch (error: any) {
      console.error('Add credits error:', error);
      toast({
        title: 'Error',
        description: error.message || 'Failed to add credits.',
        variant: 'destructive',
      });
    } finally {
      setIsAdding(false);
    }
  };

  const openAddCreditsModal = (provider: any) => {
    setSelectedProvider(provider);
    setIsAddCreditsOpen(true);
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-12 w-64" />
        <Skeleton className="h-96 w-full" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold">Providers</h2>
          <p className="text-muted-foreground">Manage provider accounts and credits</p>
        </div>
        <Badge variant="secondary" className="text-lg px-4 py-2">
          <Users className="h-4 w-4 mr-2" />
          {providers.length} Providers
        </Badge>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Provider List</CardTitle>
        </CardHeader>
        <CardContent>
          {providers.length === 0 ? (
            <div className="text-center py-12">
              <Users className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p className="text-muted-foreground">No providers registered yet.</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Email</TableHead>
                  <TableHead>Business Name</TableHead>
                  <TableHead>Destinations</TableHead>
                  <TableHead>Activities</TableHead>
                  <TableHead>Credits</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {providers.map((provider) => (
                  <TableRow key={provider.id}>
                    <TableCell className="font-medium">{provider.email}</TableCell>
                    <TableCell>{provider.service?.business_name || '-'}</TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {provider.service?.destinations?.slice(0, 2).map((dest: string) => (
                          <Badge key={dest} variant="outline" className="text-xs">
                            {dest}
                          </Badge>
                        ))}
                        {provider.service?.destinations?.length > 2 && (
                          <Badge variant="outline" className="text-xs">
                            +{provider.service.destinations.length - 2}
                          </Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {provider.service?.activity_categories?.slice(0, 2).map((activity: string) => (
                          <Badge key={activity} variant="outline" className="text-xs">
                            {activity}
                          </Badge>
                        ))}
                        {provider.service?.activity_categories?.length > 2 && (
                          <Badge variant="outline" className="text-xs">
                            +{provider.service.activity_categories.length - 2}
                          </Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">
                        {provider.wallet?.credit_balance || 0} credits
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => openAddCreditsModal(provider)}
                      >
                        <Plus className="h-3 w-3 mr-1" />
                        Add Credits
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* Add Credits Modal */}
      <Dialog open={isAddCreditsOpen} onOpenChange={setIsAddCreditsOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add Credits</DialogTitle>
            <DialogDescription>
              Add credits to {selectedProvider?.email}'s wallet
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div>
              <label className="text-sm font-medium mb-2 block">Current Balance</label>
              <div className="text-2xl font-bold">
                {selectedProvider?.wallet?.credit_balance || 0} credits
              </div>
            </div>
            <div>
              <label className="text-sm font-medium mb-2 block">Amount to Add</label>
              <Input
                type="number"
                placeholder="Enter credit amount"
                value={creditAmount}
                onChange={(e) => setCreditAmount(e.target.value)}
                min="1"
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setIsAddCreditsOpen(false);
                setCreditAmount('');
                setSelectedProvider(null);
              }}
              disabled={isAdding}
            >
              Cancel
            </Button>
            <Button onClick={handleAddCredits} disabled={isAdding || !creditAmount}>
              <Wallet className="h-4 w-4 mr-2" />
              {isAdding ? 'Adding...' : 'Add Credits'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default AdminProviders;
