import { useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { 
  Plus,
  Search,
  Eye,
  Edit,
  Trash2,
  Calendar,
  Users,
  MapPin
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { BookingForm } from '@/components/dashboard/BookingForm';

// CreateReservationDto interface based on user requirements
interface CreateReservationDto {
  establishmentId: string;
  userId: string;
  type: 'hotel' | 'restaurant' | 'tour' | 'activity';
  referenceId?: string;
  checkInDate: string;
  checkOutDate?: string;
  checkInTime?: string;
  guestsCount: number;
  specialRequests?: string;
  totalAmount: number;
}

interface Booking extends CreateReservationDto {
  id: string;
  sl: string;
  logo: string;
  customerName: string;
  establishmentName: string;
  clientName: string;
  clientEmail: string;
  clientPhone: string;
  status: 'Approved' | 'Pending' | 'Canceled';
  createdAt: string;
}

const Bookings = () => {
  const { user } = useAuth();
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [searchTerm, setSearchTerm] = useState('');
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingBooking, setEditingBooking] = useState<Booking | null>(null);

  // Sample bookings data matching CreateReservationDto structure
  const [bookings, setBookings] = useState<Booking[]>([
    {
      id: '1',
      sl: '01',
      logo: 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=100&h=100&fit=crop&crop=center',
      establishmentId: 'est_001',
      establishmentName: 'Chuijhal Hotel And Restaurant',
      userId: 'user_001',
      customerName: 'Ethan Blackwood',
      clientName: 'Ethan Blackwood',
      clientEmail: 'ethan@example.com',
      clientPhone: '123-456-789',
      type: 'hotel',
      referenceId: 'REF001',
      checkInDate: '2024-08-20',
      checkOutDate: '2024-08-24',
      checkInTime: '15:00',
      guestsCount: 2,
      specialRequests: 'Late check-in requested',
      totalAmount: 147,
      status: 'Approved',
      createdAt: '2024-08-15'
    },
    {
      id: '2',
      sl: '02',
      logo: 'https://images.unsplash.com/photo-1571896349842-33c89424de2d?w=100&h=100&fit=crop&crop=center',
      establishmentId: 'est_002',
      establishmentName: 'Green Mart Apartment',
      userId: 'user_002',
      customerName: 'Alexander Kaminski',
      clientName: 'Alexander Kaminski',
      clientEmail: 'alexander@example.com',
      clientPhone: '123-456-789',
      type: 'hotel',
      referenceId: 'REF002',
      checkInDate: '2024-08-20',
      checkOutDate: '2024-08-24',
      checkInTime: '14:00',
      guestsCount: 2,
      specialRequests: '',
      totalAmount: 147,
      status: 'Pending',
      createdAt: '2024-08-16'
    },
    {
      id: '3',
      sl: '03',
      logo: 'https://images.unsplash.com/photo-1542314831-068cd1dbfeeb?w=100&h=100&fit=crop&crop=center',
      establishmentId: 'est_003',
      establishmentName: 'Northridge University',
      userId: 'user_003',
      customerName: 'Gabriel North',
      clientName: 'Gabriel North',
      clientEmail: 'gabriel@liston.com',
      clientPhone: '123-456-789',
      type: 'restaurant',
      referenceId: 'REF003',
      checkInDate: '2024-08-20',
      checkInTime: '19:00',
      guestsCount: 2,
      specialRequests: 'Window table preferred',
      totalAmount: 147,
      status: 'Canceled',
      createdAt: '2024-08-17'
    }
  ]);

  const getStatusBadge = (status: string) => {
    const statusVariants = {
      'Approved': 'default',
      'Pending': 'secondary',
      'Canceled': 'destructive'
    } as const;
    
    return (
      <Badge variant={statusVariants[status as keyof typeof statusVariants]}>
        {status}
      </Badge>
    );
  };

  const filteredBookings = bookings.filter(booking =>
    booking.establishmentName.toLowerCase().includes(searchTerm.toLowerCase()) ||
    booking.clientName.toLowerCase().includes(searchTerm.toLowerCase()) ||
    booking.clientEmail.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleCreateBooking = (bookingData: CreateReservationDto) => {
    const newBooking: Booking = {
      ...bookingData,
      id: Date.now().toString(),
      sl: String(bookings.length + 1).padStart(2, '0'),
      logo: 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=100&h=100&fit=crop&crop=center',
      establishmentName: `Establishment ${bookingData.establishmentId}`,
      customerName: `Customer ${bookingData.userId}`,
      clientName: `Customer ${bookingData.userId}`,
      clientEmail: 'customer@example.com',
      clientPhone: '123-456-789',
      status: 'Pending',
      createdAt: new Date().toISOString().split('T')[0]
    };
    
    setBookings([...bookings, newBooking]);
    setIsFormOpen(false);
  };

  const handleEditBooking = (bookingData: CreateReservationDto) => {
    if (!editingBooking) return;
    
    const updatedBooking: Booking = {
      ...editingBooking,
      ...bookingData
    };
    
    setBookings(bookings.map(booking => 
      booking.id === editingBooking.id ? updatedBooking : booking
    ));
    setEditingBooking(null);
    setIsFormOpen(false);
  };

  const handleDeleteBooking = (id: string) => {
    setBookings(bookings.filter(booking => booking.id !== id));
  };

  const handleApproveBooking = (id: string) => {
    setBookings(bookings.map(booking => 
      booking.id === id ? { ...booking, status: 'Approved' as const } : booking
    ));
  };

  const openEditForm = (booking: Booking) => {
    setEditingBooking(booking);
    setIsFormOpen(true);
  };

  const openCreateForm = () => {
    setEditingBooking(null);
    setIsFormOpen(true);
  };

  return (
    <div className="mobile-safe-top space-y-4 lg:space-y-6 p-4 lg:p-6">
      {/* Mobile Header */}
      <div className="mobile-header">
        <h1 className="mobile-title">Booking Requests</h1>
        <p className="text-muted-foreground text-sm">
          Manage your booking requests and reservations
        </p>
      </div>

      {/* Mobile Action Button */}
      <div className="lg:hidden">
        <Dialog open={isFormOpen} onOpenChange={setIsFormOpen}>
          <DialogTrigger asChild>
            <Button onClick={openCreateForm} className="mobile-btn w-full">
              <Plus className="h-4 w-4 mr-2" />
              Create New Booking
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-[95vw] lg:max-w-2xl h-[90vh] lg:h-auto overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {editingBooking ? 'Edit Booking' : 'Create New Booking'}
              </DialogTitle>
            </DialogHeader>
            <BookingForm
              booking={editingBooking}
              onSubmit={editingBooking ? handleEditBooking : handleCreateBooking}
              onCancel={() => setIsFormOpen(false)}
            />
          </DialogContent>
        </Dialog>
      </div>

      <div className="mobile-card">
        {/* Desktop Header */}
        <div className="hidden lg:flex items-center justify-between mb-6">
          <div>
            <h2 className="text-2xl font-semibold text-foreground">Booking Requests</h2>
            <p className="text-muted-foreground mt-1">
              Duis vulputate metus fringilla, aliquet ex sed, pulvinar justo.
            </p>
          </div>
          <Dialog open={isFormOpen} onOpenChange={setIsFormOpen}>
            <DialogTrigger asChild>
              <Button onClick={openCreateForm} className="bg-primary hover:bg-primary/90">
                <Plus className="h-4 w-4 mr-2" />
                Create New Booking
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl">
              <DialogHeader>
                <DialogTitle>
                  {editingBooking ? 'Edit Booking' : 'Create New Booking'}
                </DialogTitle>
              </DialogHeader>
              <BookingForm
                booking={editingBooking}
                onSubmit={editingBooking ? handleEditBooking : handleCreateBooking}
                onCancel={() => setIsFormOpen(false)}
              />
            </DialogContent>
          </Dialog>
        </div>

        {/* Controls */}
        <div className="flex flex-col lg:flex-row lg:items-center justify-between mb-6 space-y-4 lg:space-y-0">
          <div className="flex items-center space-x-2">
            <span className="text-sm text-muted-foreground">Show</span>
            <Select value={itemsPerPage.toString()} onValueChange={(value) => setItemsPerPage(Number(value))}>
              <SelectTrigger className="w-20">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="10">10</SelectItem>
                <SelectItem value="25">25</SelectItem>
                <SelectItem value="50">50</SelectItem>
                <SelectItem value="100">100</SelectItem>
              </SelectContent>
            </Select>
            <span className="text-sm text-muted-foreground">entries</span>
          </div>
          
          <div className="flex items-center space-x-2">
            <span className="text-sm text-muted-foreground hidden lg:block">Search:</span>
            <div className="relative flex-1 lg:flex-none">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search bookings..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="mobile-input pl-10 lg:w-64"
              />
            </div>
          </div>
        </div>

        {/* Mobile Cards */}
        <div className="lg:hidden space-y-4">
          {filteredBookings.map((booking) => (
            <div key={booking.id} className="mobile-card border border-border bg-card">
              <div className="p-4 space-y-3">
                <div className="flex items-start justify-between">
                  <div className="flex items-center space-x-3">
                    <Avatar className="h-12 w-12">
                      <AvatarImage src={booking.logo} alt="Logo" />
                      <AvatarFallback>{booking.establishmentName.charAt(0)}</AvatarFallback>
                    </Avatar>
                    <div>
                      <h3 className="font-medium">{booking.establishmentName}</h3>
                      <p className="text-sm text-muted-foreground">#{booking.sl}</p>
                    </div>
                  </div>
                  {getStatusBadge(booking.status)}
                </div>
                
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <div className="flex items-center space-x-1 text-muted-foreground">
                      <Calendar className="h-4 w-4" />
                      <span>Date</span>
                    </div>
                    <p className="font-medium">{booking.checkInDate}</p>
                    {booking.checkOutDate && <p className="text-xs text-muted-foreground">to {booking.checkOutDate}</p>}
                  </div>
                  <div>
                    <div className="flex items-center space-x-1 text-muted-foreground">
                      <Users className="h-4 w-4" />
                      <span>Guests</span>
                    </div>
                    <p className="font-medium">{booking.guestsCount} {booking.guestsCount === 1 ? 'Guest' : 'Guests'}</p>
                  </div>
                </div>

                <div className="border-t pt-3">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm text-muted-foreground">Client</span>
                    <span className="text-lg font-bold text-primary">${booking.totalAmount}</span>
                  </div>
                  <div className="text-sm">
                    <p className="font-medium">{booking.clientName}</p>
                    <p className="text-muted-foreground">{booking.clientEmail}</p>
                    <p className="text-muted-foreground">{booking.clientPhone}</p>
                  </div>
                </div>

                <div className="flex flex-wrap gap-2 pt-2">
                  <Button variant="outline" size="sm" className="flex-1">
                    <Eye className="h-4 w-4 mr-1" />
                    View
                  </Button>
                  <Button 
                    variant="outline" 
                    size="sm" 
                    className="flex-1"
                    onClick={() => openEditForm(booking)}
                  >
                    <Edit className="h-4 w-4 mr-1" />
                    Edit
                  </Button>
                  {booking.status === 'Pending' && (
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="flex-1 text-green-600 hover:text-green-700 hover:bg-green-50"
                      onClick={() => handleApproveBooking(booking.id)}
                    >
                      Approve
                    </Button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Desktop Table */}
        <div className="hidden lg:block border rounded-lg overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/50">
                <TableHead className="w-16">SL</TableHead>
                <TableHead className="w-16">Logo</TableHead>
                <TableHead>Customer</TableHead>
                <TableHead>Booking Date</TableHead>
                <TableHead>Persons</TableHead>
                <TableHead>Price</TableHead>
                <TableHead>Client</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-32">Action</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredBookings.map((booking) => (
                <TableRow key={booking.id} className="hover:bg-muted/30">
                  <TableCell className="font-medium">{booking.sl}</TableCell>
                  <TableCell>
                    <Avatar className="h-10 w-10">
                      <AvatarImage src={booking.logo} alt="Logo" />
                      <AvatarFallback>{booking.establishmentName.charAt(0)}</AvatarFallback>
                    </Avatar>
                  </TableCell>
                  <TableCell className="font-medium">{booking.establishmentName}</TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-1">
                      <Calendar className="h-4 w-4 text-muted-foreground" />
                      <span>{booking.checkInDate}</span>
                      {booking.checkOutDate && <span> - {booking.checkOutDate}</span>}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-1">
                      <Users className="h-4 w-4 text-muted-foreground" />
                      <span>{booking.guestsCount} {booking.guestsCount === 1 ? 'Guest' : 'Guests'}</span>
                    </div>
                  </TableCell>
                  <TableCell className="font-semibold text-primary">${booking.totalAmount}</TableCell>
                  <TableCell>
                    <div className="space-y-1">
                      <div className="font-medium">{booking.clientName}</div>
                      <div className="text-sm text-muted-foreground">{booking.clientEmail}</div>
                      <div className="text-sm text-muted-foreground">{booking.clientPhone}</div>
                    </div>
                  </TableCell>
                  <TableCell>{getStatusBadge(booking.status)}</TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-1">
                      <Button variant="outline" size="sm" className="h-8 w-8 p-0">
                        <Eye className="h-4 w-4" />
                      </Button>
                      <Button 
                        variant="outline" 
                        size="sm" 
                        className="h-8 w-8 p-0"
                        onClick={() => openEditForm(booking)}
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      {booking.status === 'Pending' && (
                        <Button 
                          variant="outline" 
                          size="sm" 
                          className="h-8 px-2 text-green-600 hover:text-green-700 hover:bg-green-50"
                          onClick={() => handleApproveBooking(booking.id)}
                        >
                          Approve
                        </Button>
                      )}
                      <Button 
                        variant="outline" 
                        size="sm" 
                        className="h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"
                        onClick={() => handleDeleteBooking(booking.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {/* Pagination */}
        <div className="flex flex-col lg:flex-row items-center justify-between mt-6 space-y-4 lg:space-y-0">
          <div>
            <span className="text-sm text-muted-foreground">
              Showing 1 to {filteredBookings.length} of {filteredBookings.length} entries
            </span>
          </div>
          <div className="flex items-center space-x-2">
            <Button variant="outline" size="sm" disabled>
              Previous
            </Button>
            <Button variant="outline" size="sm" className="bg-primary text-primary-foreground">
              1
            </Button>
            <Button variant="outline" size="sm" disabled>
              Next
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Bookings;