import { Clock, ExternalLink, MapPin, Plus, Star } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } 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 BusinessPlace {
  id: string;
  status: string;
  claimed_at: string;
  places: {
    id: string;
    name: string;
    description: string | null;
    type: string | null;
    city: string | null;
    country: string | null;
    rating: number | null;
    image_url: string | null;
  };
}

const BusinessPlaces = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [business, setBusiness] = useState<any>(null);
  const [places, setPlaces] = useState<BusinessPlace[]>([]);
  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 placesData = await businessesApi.getPlaces(businessData.id);
      setPlaces(placesData);
    } catch (error) {
      console.error('Veri yükleme hatası:', error);
      toast({
        title: 'Hata',
        description: 'Veriler yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      pending: { label: 'Beklemede', variant: 'secondary' as const },
      approved: { label: 'Onaylandı', variant: 'default' as const },
      rejected: { label: 'Reddedildi', variant: 'destructive' as const },
    };
    
    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.pending;
    return <Badge variant={config.variant}>{config.label}</Badge>;
  };

  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-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3].map(i => (
            <Skeleton key={i} className="h-64 bg-muted" />
          ))}
        </div>
      </div>
    );
  }

  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">Yerlerim</h1>
          <p className="text-muted-foreground mt-1">
            İşletmenize ait yerleri yönetin
          </p>
        </div>
        <Button onClick={() => navigate('/business/add-place')}>
          <Plus className="h-4 w-4 mr-2" />
          Yeni Yer Ekle
        </Button>
      </div>

      {/* Places Grid */}
      {places.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {places.map((businessPlace) => {
            const place = businessPlace.places;
            return (
              <Card key={businessPlace.id} className="overflow-hidden hover:shadow-lg transition-shadow">
                <div className="relative aspect-video">
                  {place.image_url ? (
                    <img src={place.image_url} alt={place.name} className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center">
                      <MapPin className="h-12 w-12 text-primary/40" />
                    </div>
                  )}
                  <div className="absolute top-3 right-3">
                    {getStatusBadge(businessPlace.status)}
                  </div>
                </div>
                <CardContent className="p-4">
                  <div className="flex justify-between items-start mb-2">
                    <h3 className="font-bold text-lg truncate pr-2">{place.name}</h3>
                    {place.rating && (
                      <div className="flex items-center gap-1 text-sm font-bold text-primary">
                        <Star className="h-4 w-4 fill-primary" /> {place.rating}
                      </div>
                    )}
                  </div>
                  
                  {place.type && (
                    <Badge variant="outline" className="mb-2">{place.type}</Badge>
                  )}
                  
                  {(place.city || place.country) && (
                    <div className="flex items-center text-sm text-muted-foreground mb-3">
                      <MapPin className="h-3 w-3 mr-1" />
                      {[place.city, place.country].filter(Boolean).join(', ')}
                    </div>
                  )}

                  {businessPlace.status === 'pending' && (
                    <div className="flex items-center text-xs text-muted-foreground mb-3">
                      <Clock className="h-3 w-3 mr-1" />
                      Onay bekliyor
                    </div>
                  )}

                  <div className="flex gap-2">
                    <Button 
                      size="sm" 
                      variant="outline" 
                      className="flex-1"
                      onClick={() => navigate(`/explore?place=${place.id}`)}
                    >
                      <ExternalLink className="h-3 w-3 mr-1" />
                      Görüntüle
                    </Button>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      ) : (
        <div className="flex flex-col items-center justify-center py-32 text-center">
          <div className="w-20 h-20 rounded-full bg-muted flex items-center justify-center mb-6">
            <MapPin className="h-10 w-10 text-muted-foreground opacity-30" />
          </div>
          <h2 className="text-2xl font-bold mb-2">Henüz yer eklenmemiş</h2>
          <p className="text-muted-foreground max-w-sm mb-8">
            İşletmenize ait yerleri ekleyerek gezginlere ulaşın.
          </p>
          <Button onClick={() => navigate('/business/add-place')}>
            <Plus className="h-4 w-4 mr-2" />
            İlk Yerinizi Ekleyin
          </Button>
        </div>
      )}
    </div>
  );
};

export default BusinessPlaces;
