import { useState } from 'react';
import DashboardLayout from '@/components/DashboardLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { SearchBar } from '@/components/shared/SearchBar';
import { useSearch } from '@/hooks/useSearch';
import { MapPin, Star, Loader2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';

const SearchPlaces = () => {
  const [category, setCategory] = useState<string>('all');
  const [minRating, setMinRating] = useState<number>(0);
  const { searching, results, searchPlaces } = useSearch();

  const handleSearch = (query: string) => {
    if (query.trim()) {
      searchPlaces(query, {
        category: category !== 'all' ? category : undefined,
        minRating: minRating > 0 ? minRating : undefined,
      });
    }
  };

  const renderStars = (rating: number) => {
    return Array.from({ length: 5 }, (_, i) => (
      <Star
        key={i}
        size={14}
        className={i < rating ? "text-yellow-400 fill-yellow-400" : "text-muted-foreground"}
      />
    ));
  };

  return (
    <DashboardLayout>
      <div className="p-6 space-y-6">
        {/* Header */}
        <div>
          <h1 className="text-3xl font-bold">Buscar Lugares</h1>
          <p className="text-muted-foreground mt-1">
            Encuentra lugares de interés turístico
          </p>
        </div>

        {/* Search and Filters */}
        <Card>
          <CardHeader>
            <CardTitle>Búsqueda</CardTitle>
            <CardDescription>
              Usa filtros para refinar tu búsqueda
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <SearchBar
              onSearch={handleSearch}
              placeholder="Buscar por nombre, descripción..."
              loading={searching}
            />
            
            <div className="flex gap-4">
              <div className="flex-1">
                <label className="text-sm font-medium mb-2 block">Categoría</label>
                <Select value={category} onValueChange={setCategory}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Todas</SelectItem>
                    <SelectItem value="beach">Playas</SelectItem>
                    <SelectItem value="museum">Museos</SelectItem>
                    <SelectItem value="park">Parques</SelectItem>
                    <SelectItem value="restaurant">Restaurantes</SelectItem>
                    <SelectItem value="hotel">Hoteles</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div className="flex-1">
                <label className="text-sm font-medium mb-2 block">Calificación Mínima</label>
                <Select value={minRating.toString()} onValueChange={(v) => setMinRating(Number(v))}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="0">Todas</SelectItem>
                    <SelectItem value="3">3+ ⭐</SelectItem>
                    <SelectItem value="4">4+ ⭐</SelectItem>
                    <SelectItem value="4.5">4.5+ ⭐</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Results */}
        {searching && (
          <div className="flex justify-center items-center py-12">
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
          </div>
        )}

        {!searching && results.length === 0 && (
          <Card>
            <CardContent className="py-12">
              <div className="text-center text-muted-foreground">
                <MapPin className="w-12 h-12 mx-auto mb-4 opacity-50" />
                <p>No hay resultados para mostrar</p>
                <p className="text-sm mt-2">Intenta realizar una búsqueda</p>
              </div>
            </CardContent>
          </Card>
        )}

        {!searching && results.length > 0 && (
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {results.map((place: any) => (
              <Card key={place.id} className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <CardTitle className="text-lg">{place.name}</CardTitle>
                      <div className="flex items-center gap-2 mt-2">
                        <div className="flex items-center gap-1">
                          {renderStars(Math.floor(place.rating))}
                        </div>
                        <span className="text-sm font-medium">{place.rating.toFixed(1)}</span>
                      </div>
                    </div>
                    {place.category && (
                      <Badge variant="secondary" className="capitalize">
                        {place.category}
                      </Badge>
                    )}
                  </div>
                </CardHeader>
                <CardContent className="space-y-3">
                  <p className="text-sm text-muted-foreground line-clamp-2">
                    {place.description}
                  </p>
                  {place.location && (
                    <div className="flex items-start gap-2 text-sm">
                      <MapPin className="w-4 h-4 mt-0.5 text-muted-foreground flex-shrink-0" />
                      <span className="text-muted-foreground">{place.location.address}</span>
                    </div>
                  )}
                  <div className="flex items-center justify-between pt-2 border-t">
                    <Badge variant={place.status === 'active' ? 'default' : 'secondary'}>
                      {place.status === 'active' ? 'Activo' : 'Inactivo'}
                    </Badge>
                    <span className="text-xs text-muted-foreground">
                      {new Date(place.createdAt).toLocaleDateString('es')}
                    </span>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </DashboardLayout>
  );
};

export default SearchPlaces;
