import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { 
  Settings, 
  Zap, 
  TrendingUp, 
  Calendar, 
  Users, 
  DollarSign,
  Plus,
  Search,
  Filter,
  MoreHorizontal,
  CheckCircle,
  AlertTriangle,
  XCircle,
  RefreshCw,
  Eye,
  Edit,
  Trash2,
  Hotel,
  Utensils,
  Car,
  Plane,
  MapPin,
  Globe
} from 'lucide-react';
import { useChannelManager } from '@/hooks/useChannelManager';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';

const ChannelManager = () => {
  const {
    channels,
    listings,
    reservations,
    stats,
    loading,
    error,
    connectChannel,
    disconnectChannel,
    syncChannel,
    createListing,
    clearError
  } = useChannelManager();

  const [activeTab, setActiveTab] = useState('overview');
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [showConnectModal, setShowConnectModal] = useState(false);

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'connected':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'syncing':
        return <RefreshCw className="w-4 h-4 text-blue-500 animate-spin" />;
      case 'error':
        return <AlertTriangle className="w-4 h-4 text-yellow-500" />;
      default:
        return <XCircle className="w-4 h-4 text-red-500" />;
    }
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'hotel':
        return <Hotel className="w-4 h-4" />;
      case 'restaurant':
        return <Utensils className="w-4 h-4" />;
      case 'vehicle':
        return <Car className="w-4 h-4" />;
      case 'flight':
        return <Plane className="w-4 h-4" />;
      case 'activity':
        return <MapPin className="w-4 h-4" />;
      default:
        return <Globe className="w-4 h-4" />;
    }
  };

  const OverviewTab = () => (
    <div className="space-y-6">
      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Ingresos Totales</p>
                <p className="text-2xl font-bold">${stats?.totalRevenue.toLocaleString() || '0'}</p>
              </div>
              <DollarSign className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Reservas Totales</p>
                <p className="text-2xl font-bold">{stats?.totalBookings || 0}</p>
              </div>
              <Calendar className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Tasa de Ocupación</p>
                <p className="text-2xl font-bold">{stats?.occupancyRate || 0}%</p>
              </div>
              <TrendingUp className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Canales Conectados</p>
                <p className="text-2xl font-bold">{channels.filter(c => c.status === 'connected').length}</p>
              </div>
              <Zap className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Channel Performance */}
      <Card>
        <CardHeader>
          <CardTitle>Rendimiento por Canal</CardTitle>
          <CardDescription>Ingresos y reservas por cada canal de distribución</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {stats?.channelPerformance.map((channel, index) => (
              <div key={index} className="flex items-center justify-between p-4 border rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-primary/10 rounded-lg flex items-center justify-center">
                    <Globe className="w-5 h-5 text-primary" />
                  </div>
                  <div>
                    <p className="font-medium">{channel.channelName}</p>
                    <p className="text-sm text-muted-foreground">{channel.bookings} reservas</p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="font-semibold">${channel.revenue.toLocaleString()}</p>
                  <p className="text-sm text-muted-foreground">Ingresos</p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Recent Reservations */}
      <Card>
        <CardHeader>
          <CardTitle>Reservas Recientes</CardTitle>
          <CardDescription>Últimas reservas recibidas en todos los canales</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {reservations.slice(0, 5).map((reservation) => (
              <div key={reservation.id} className="flex items-center justify-between p-3 border rounded-lg">
                <div className="flex items-center space-x-3">
                  {getTypeIcon(reservation.listingType)}
                  <div>
                    <p className="font-medium">{reservation.guestName}</p>
                    <p className="text-sm text-muted-foreground">{reservation.listingName}</p>
                  </div>
                </div>
                <div className="text-right">
                  <Badge variant={
                    reservation.status === 'confirmed' ? 'default' :
                    reservation.status === 'pending' ? 'secondary' :
                    reservation.status === 'cancelled' ? 'destructive' : 'outline'
                  }>
                    {reservation.status}
                  </Badge>
                  <p className="text-sm text-muted-foreground mt-1">
                    ${reservation.totalAmount.toLocaleString()}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );

  const ChannelsTab = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold">Gestión de Canales</h2>
          <p className="text-muted-foreground">Conecta y administra tus canales de distribución</p>
        </div>
        <Button onClick={() => setShowConnectModal(true)}>
          <Plus className="w-4 h-4 mr-2" />
          Conectar Canal
        </Button>
      </div>

      <div className="grid gap-4">
        {channels.map((channel) => (
          <Card key={channel.id}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center">
                    <Globe className="w-6 h-6 text-primary" />
                  </div>
                  <div>
                    <div className="flex items-center space-x-2">
                      <h3 className="text-lg font-semibold">{channel.name}</h3>
                      {getStatusIcon(channel.status)}
                      <Badge variant="outline">{channel.type}</Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      Última sincronización: {format(new Date(channel.lastSync), 'dd/MM/yyyy HH:mm', { locale: es })}
                    </p>
                    <p className="text-sm text-muted-foreground">
                      {channel.properties.length} propiedades conectadas
                    </p>
                  </div>
                </div>
                
                <div className="flex items-center space-x-4">
                  <div className="text-right">
                    <p className="text-2xl font-bold">${channel.revenue.toLocaleString()}</p>
                    <p className="text-sm text-muted-foreground">{channel.bookings} reservas</p>
                    <p className="text-xs text-muted-foreground">Comisión: {channel.commission}%</p>
                  </div>
                  
                  <div className="flex space-x-2">
                    <Button 
                      variant="outline" 
                      size="sm"
                      onClick={() => syncChannel(channel.id)}
                      disabled={loading}
                    >
                      <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Settings className="w-4 h-4" />
                    </Button>
                    <Button 
                      variant="outline" 
                      size="sm"
                      onClick={() => disconnectChannel(channel.id)}
                    >
                      <XCircle className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );

  const ListingsTab = () => {
    const filteredListings = listings.filter(listing => {
      const matchesSearch = listing.name.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesType = filterType === 'all' || listing.type === filterType;
      return matchesSearch && matchesType;
    });

    return (
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <div>
            <h2 className="text-2xl font-bold">Gestión de Propiedades</h2>
            <p className="text-muted-foreground">Administra hoteles, restaurantes, vehículos y más</p>
          </div>
          <Button>
            <Plus className="w-4 h-4 mr-2" />
            Nueva Propiedad
          </Button>
        </div>

        <div className="flex space-x-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
            <Input
              placeholder="Buscar propiedades..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={filterType} onValueChange={setFilterType}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="Filtrar por tipo" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Todos los tipos</SelectItem>
              <SelectItem value="hotel">Hoteles</SelectItem>
              <SelectItem value="restaurant">Restaurantes</SelectItem>
              <SelectItem value="vehicle">Vehículos</SelectItem>
              <SelectItem value="flight">Vuelos</SelectItem>
              <SelectItem value="activity">Actividades</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div className="grid gap-4">
          {filteredListings.map((listing) => (
            <Card key={listing.id}>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-4">
                    <div className="w-16 h-16 bg-muted rounded-lg flex items-center justify-center">
                      {listing.images[0] ? (
                        <img 
                          src={listing.images[0]} 
                          alt={listing.name}
                          className="w-full h-full object-cover rounded-lg"
                        />
                      ) : (
                        getTypeIcon(listing.type)
                      )}
                    </div>
                    <div>
                      <div className="flex items-center space-x-2">
                        <h3 className="text-lg font-semibold">{listing.name}</h3>
                        <Badge variant={listing.status === 'active' ? 'default' : 'secondary'}>
                          {listing.status}
                        </Badge>
                        <Badge variant="outline">{listing.type}</Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">{listing.location.address}</p>
                      <p className="text-sm text-muted-foreground">
                        Conectado a {listing.channels.length} canales
                      </p>
                    </div>
                  </div>
                  
                  <div className="flex items-center space-x-4">
                    <div className="text-right">
                      <p className="text-xl font-bold">${listing.basePrice}</p>
                      <p className="text-sm text-muted-foreground">
                        {listing.availability ? 'Disponible' : 'No disponible'}
                      </p>
                    </div>
                    
                    <div className="flex space-x-2">
                      <Button variant="outline" size="sm">
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button variant="outline" size="sm">
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button variant="outline" size="sm">
                        <MoreHorizontal className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    );
  };

  const ReservationsTab = () => (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold">Gestión de Reservas</h2>
          <p className="text-muted-foreground">Administra todas las reservas desde un solo lugar</p>
        </div>
      </div>

      <div className="grid gap-4">
        {reservations.map((reservation) => (
          <Card key={reservation.id}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  {getTypeIcon(reservation.listingType)}
                  <div>
                    <div className="flex items-center space-x-2">
                      <h3 className="text-lg font-semibold">{reservation.guestName}</h3>
                      <Badge variant={
                        reservation.status === 'confirmed' ? 'default' :
                        reservation.status === 'pending' ? 'secondary' :
                        reservation.status === 'cancelled' ? 'destructive' : 'outline'
                      }>
                        {reservation.status}
                      </Badge>
                    </div>
                    <p className="text-sm font-medium">{reservation.listingName}</p>
                    <p className="text-sm text-muted-foreground">
                      {format(new Date(reservation.checkIn), 'dd/MM/yyyy', { locale: es })}
                      {reservation.checkOut && ` - ${format(new Date(reservation.checkOut), 'dd/MM/yyyy', { locale: es })}`}
                    </p>
                    <p className="text-sm text-muted-foreground">
                      {reservation.guests} huéspedes • {reservation.channel}
                    </p>
                  </div>
                </div>
                
                <div className="flex items-center space-x-4">
                  <div className="text-right">
                    <p className="text-xl font-bold">${reservation.totalAmount.toLocaleString()}</p>
                    <p className="text-sm text-muted-foreground">
                      Pago: <Badge variant={reservation.paymentStatus === 'paid' ? 'default' : 'secondary'}>
                        {reservation.paymentStatus}
                      </Badge>
                    </p>
                  </div>
                  
                  <div className="flex space-x-2">
                    <Button variant="outline" size="sm">
                      <Eye className="w-4 h-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <MoreHorizontal className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <AlertTriangle className="w-12 h-12 text-yellow-500 mx-auto mb-4" />
          <h3 className="text-lg font-semibold mb-2">Error al cargar datos</h3>
          <p className="text-muted-foreground mb-4">{error}</p>
          <Button onClick={clearError}>Reintentar</Button>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Channel Manager</h1>
          <p className="text-muted-foreground">
            Gestiona todas tus propiedades y canales de distribución desde un solo lugar
          </p>
        </div>
        <div className="flex space-x-2">
          <Button variant="outline">
            <RefreshCw className="w-4 h-4 mr-2" />
            Sincronizar Todo
          </Button>
          <Button>
            <Settings className="w-4 h-4 mr-2" />
            Configuración
          </Button>
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="overview">Resumen</TabsTrigger>
          <TabsTrigger value="channels">Canales</TabsTrigger>
          <TabsTrigger value="listings">Propiedades</TabsTrigger>
          <TabsTrigger value="reservations">Reservas</TabsTrigger>
        </TabsList>

        <TabsContent value="overview">
          <OverviewTab />
        </TabsContent>

        <TabsContent value="channels">
          <ChannelsTab />
        </TabsContent>

        <TabsContent value="listings">
          <ListingsTab />
        </TabsContent>

        <TabsContent value="reservations">
          <ReservationsTab />
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default ChannelManager;