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 { Building2, Star, Loader2, MapPin, CheckCircle } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';

const SearchEstablishments = () => {
  const [type, setType] = useState<string>('all');
  const [minRating, setMinRating] = useState<number>(0);
  const [verifiedOnly, setVerifiedOnly] = useState(false);
  const { searching, results, searchEstablishments } = useSearch();

  const handleSearch = (query: string) => {
    if (query.trim()) {
      searchEstablishments(query, {
        type: type !== 'all' ? type : undefined,
        minRating: minRating > 0 ? minRating : undefined,
        verified: verifiedOnly,
      });
    }
  };

  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"}
      />
    ));
  };

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      restaurant: 'Restaurante',
      hotel: 'Hotel',
      shop: 'Tienda',
      attraction: 'Atracción',
    };
    return labels[type] || type;
  };

  return (
    <DashboardLayout>
      <div className="p-6 space-y-6">
        {/* Header */}
        <div>
          <h1 className="text-3xl font-bold">Buscar Establecimientos</h1>
          <p className="text-muted-foreground mt-1">
            Encuentra hoteles, restaurantes, tiendas y más
          </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 establecimientos..."
              loading={searching}
            />
            
            <div className="grid gap-4 md:grid-cols-3">
              <div>
                <label className="text-sm font-medium mb-2 block">Tipo</label>
                <Select value={type} onValueChange={setType}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Todos</SelectItem>
                    <SelectItem value="restaurant">Restaurantes</SelectItem>
                    <SelectItem value="hotel">Hoteles</SelectItem>
                    <SelectItem value="shop">Tiendas</SelectItem>
                    <SelectItem value="attraction">Atracciones</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <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>
                <label className="text-sm font-medium mb-2 block">Filtros</label>
                <div className="flex items-center space-x-2 h-10">
                  <Switch
                    id="verified"
                    checked={verifiedOnly}
                    onCheckedChange={setVerifiedOnly}
                  />
                  <Label htmlFor="verified" className="cursor-pointer">
                    Solo verificados
                  </Label>
                </div>
              </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">
                <Building2 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((establishment: any) => (
              <Card key={establishment.id} className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <CardTitle className="text-lg">{establishment.name}</CardTitle>
                        {establishment.verified && (
                          <CheckCircle className="w-4 h-4 text-blue-500" />
                        )}
                      </div>
                      <div className="flex items-center gap-2 mt-2">
                        <div className="flex items-center gap-1">
                          {renderStars(Math.floor(establishment.rating))}
                        </div>
                        <span className="text-sm font-medium">{establishment.rating.toFixed(1)}</span>
                      </div>
                    </div>
                    <Badge variant="secondary" className="capitalize">
                      {getTypeLabel(establishment.type)}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent className="space-y-3">
                  <p className="text-sm text-muted-foreground line-clamp-2">
                    {establishment.description}
                  </p>
                  
                  {establishment.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">{establishment.location.address}</span>
                    </div>
                  )}

                  {establishment.owner && (
                    <div className="text-sm">
                      <span className="text-muted-foreground">Propietario: </span>
                      <span className="font-medium">{establishment.owner.name}</span>
                    </div>
                  )}

                  <div className="flex items-center justify-between pt-2 border-t">
                    <Badge 
                      variant={
                        establishment.status === 'active' ? 'default' : 
                        establishment.status === 'pending' ? 'secondary' : 
                        'destructive'
                      }
                    >
                      {establishment.status === 'active' ? 'Activo' : 
                       establishment.status === 'pending' ? 'Pendiente' : 
                       'Suspendido'}
                    </Badge>
                    <span className="text-xs text-muted-foreground">
                      {new Date(establishment.createdAt).toLocaleDateString('es')}
                    </span>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </DashboardLayout>
  );
};

export default SearchEstablishments;
