import { Building2, MapPin, Plus, Settings, TrendingUp, Users } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useAuth } from '@/contexts/AuthContext';
import { businessesApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';

interface Business {
  id: string;
  name: string;
  description: string | null;
  category: string | null;
  verified: boolean;
}

interface BusinessStats {
  total_places: number;
  approved_places: number;
  total_bookmarks: number;
}

const BusinessDashboard = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [business, setBusiness] = useState<Business | null>(null);
  const [stats, setStats] = useState<BusinessStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!user) {
      navigate('/business/register');
      return;
    }
    loadData();
  }, [user]);

  const loadData = async () => {
    try {
      setLoading(true);
      const businessData = await businessesApi.getUserBusiness();
      
      if (!businessData) {
        navigate('/business/register');
        return;
      }

      setBusiness(businessData);
      
      const statsData = await businessesApi.getStats(businessData.id);
      setStats(statsData);
    } catch (error) {
      console.error('Veri yükleme hatası:', error);
      toast({
        title: 'Hata',
        description: 'Veriler yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Skeleton className="h-12 w-64 mb-8 bg-muted" />
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
          {[1, 2, 3].map(i => (
            <Skeleton key={i} className="h-32 bg-muted" />
          ))}
        </div>
      </div>
    );
  }

  if (!business) {
    return null;
  }

  const statCards = [
    {
      title: 'Toplam Yerler',
      value: stats?.total_places || 0,
      icon: MapPin,
      color: 'text-blue-600',
      bgColor: 'bg-blue-50',
    },
    {
      title: 'Onaylı Yerler',
      value: stats?.approved_places || 0,
      icon: TrendingUp,
      color: 'text-green-600',
      bgColor: 'bg-green-50',
    },
    {
      title: 'Toplam Kayıt',
      value: stats?.total_bookmarks || 0,
      icon: Users,
      color: 'text-purple-600',
      bgColor: 'bg-purple-50',
    },
  ];

  return (
    <div className="container mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold flex items-center gap-3">
            <Building2 className="h-8 w-8 text-primary" />
            {business.name}
          </h1>
          {business.verified && (
            <p className="text-sm text-muted-foreground mt-1">
              ✓ Doğrulanmış İşletme
            </p>
          )}
        </div>
        <Button
          variant="outline"
          onClick={() => navigate('/business/settings')}
        >
          <Settings className="h-4 w-4 mr-2" />
          Ayarlar
        </Button>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        {statCards.map((stat, index) => (
          <Card key={index}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground mb-1">{stat.title}</p>
                  <p className="text-3xl font-bold">{stat.value}</p>
                </div>
                <div className={`p-3 rounded-full ${stat.bgColor}`}>
                  <stat.icon className={`h-6 w-6 ${stat.color}`} />
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Quick Actions */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card className="cursor-pointer hover:shadow-lg transition-shadow" onClick={() => navigate('/business/places')}>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5" />
              Yerlerinizi Yönetin
            </CardTitle>
            <CardDescription>
              Mevcut yerlerinizi görüntüleyin ve düzenleyin
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Button className="w-full">
              Yerleri Görüntüle
            </Button>
          </CardContent>
        </Card>

        <Card className="cursor-pointer hover:shadow-lg transition-shadow" onClick={() => navigate('/business/add-place')}>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Plus className="h-5 w-5" />
              Yeni Yer Ekleyin
            </CardTitle>
            <CardDescription>
              Platformda yeni bir yer oluşturun
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Button className="w-full" variant="outline">
              Yer Ekle
            </Button>
          </CardContent>
        </Card>
      </div>

      {/* Info Banner */}
      <Card className="mt-8 bg-gradient-to-r from-primary/10 to-accent/10 border-none">
        <CardContent className="p-6">
          <h3 className="font-bold text-lg mb-2">İşletmenizi Büyütün</h3>
          <p className="text-muted-foreground mb-4">
            LetsGoCappadocia'da işletmenizi tanıtarak daha fazla müşteriye ulaşın. 
            Yerlerinizi ekleyin, fotoğraflar paylaşın ve gezginlerle etkileşime geçin.
          </p>
          <Button>Daha Fazla Bilgi</Button>
        </CardContent>
      </Card>
    </div>
  );
};

export default BusinessDashboard;
