'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Filter, Download, Eye, XCircle } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import Pagination from '@/components/ui/Pagination';
import ActionButton from '@/components/ui/ActionButton';
import { bookingsApi } from '@/lib/api';
import { formatCurrency, formatDateTime } from '@/lib/utils';
import { BookingFilters } from '@/types';

export default function BookingsPage() {
  const [filters, setFilters] = useState<BookingFilters>({
    page: 1,
    pageSize: 20,
    search: '',
    status: '',
  });

  const queryClient = useQueryClient();

  const { data, isLoading, error } = useQuery({
    queryKey: ['bookings', filters],
    queryFn: () => bookingsApi.getAll(filters),
  });

  if (error) {
    console.error('Bookings API Error:', error);
  }

  const cancelMutation = useMutation({
    mutationFn: ({ id, reason }: { id: string; reason?: string }) => bookingsApi.cancel(id, reason),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['bookings'] });
      alert('Booking cancelled successfully');
    },
  });

  const handleCancel = async (booking: any) => {
    if (confirm(`Are you sure you want to cancel booking ${booking.bookingRef}?`)) {
      await cancelMutation.mutateAsync({ id: booking.id, reason: 'Cancelled by admin' });
    }
  };

  const columns = [
    { 
      key: 'bookingRef', 
      label: 'Reference',
      sortable: true,
      render: (booking: any) => (
        <span className="font-mono font-semibold">{booking.bookingRef}</span>
      ),
    },
    { 
      key: 'passenger', 
      label: 'Passenger',
      render: (booking: any) => (
        <div>
          <div className="font-medium">{booking.passenger?.fullName || booking.contactEmail || 'Guest'}</div>
          <div className="text-sm text-muted-foreground">{booking.contactPhone || booking.passenger?.phone}</div>
        </div>
      ),
    },
    { 
      key: 'status', 
      label: 'Status',
      render: (booking: any) => (
        <Badge variant="status" status={booking.status}>{booking.status}</Badge>
      ),
    },
    { 
      key: 'totalMinor', 
      label: 'Amount',
      sortable: true,
      render: (booking: any) => formatCurrency(booking.totalMinor, booking.currency),
    },
    { 
      key: 'paymentStatus', 
      label: 'Payment',
      render: (booking: any) => (
        <Badge variant="status" status={booking.paymentIntent?.status || 'PENDING'}>
          {booking.paymentIntent?.status || 'PENDING'}
        </Badge>
      ),
    },
    { 
      key: 'createdAt', 
      label: 'Created',
      sortable: true,
      render: (booking: any) => formatDateTime(booking.createdAt),
    },
  ];

  const actions = [
    // TODO: Create booking detail page
    // {
    //   label: 'View Details',
    //   onClick: (booking: any) => window.location.href = `/bookings/${booking.id}`,
    //   variant: 'secondary' as const,
    //   icon: Eye,
    // },
    {
      label: 'Cancel Booking',
      onClick: handleCancel,
      variant: 'danger' as const,
      icon: XCircle,
      show: (booking: any) => booking.status !== 'CANCELLED' && booking.status !== 'COMPLETED',
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Bookings</h1>
          <p className="text-muted-foreground">Manage all passenger bookings</p>
        </div>
        <ActionButton variant="export" icon={Download}>Export</ActionButton>
      </div>

      <div className="card">
        {error && (
          <div className="mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 p-4 text-sm text-red-800 dark:text-red-200">
            Error loading bookings: {error instanceof Error ? error.message : 'Unknown error'}
          </div>
        )}
        <div className="mb-4 flex flex-wrap gap-4">
          <div className="flex-1">
            <input
              type="text"
              placeholder="Search by reference, email, or phone..."
              className="input"
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value, page: 1 })}
            />
          </div>
          <select
            className="input w-48"
            value={filters.status}
            onChange={(e) => setFilters({ ...filters, status: e.target.value || undefined, page: 1 })}
          >
            <option value="">All Status</option>
            <option value="PENDING_PAYMENT">Pending Payment</option>
            <option value="CONFIRMED">Confirmed</option>
            <option value="CANCELLED">Cancelled</option>
            <option value="COMPLETED">Completed</option>
          </select>
          <ActionButton variant="secondary" icon={Filter}>More Filters</ActionButton>
        </div>

        <DataTable
          data={data?.items || []}
          columns={columns}
          actions={actions}
          loading={isLoading}
          emptyMessage="No bookings found"
        />
        
        {data?.meta && (
          <Pagination
            currentPage={data.meta.page}
            totalPages={data.meta.totalPages}
            onPageChange={(page) => setFilters({ ...filters, page })}
          />
        )}
      </div>
    </div>
  );
}
