'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Filter, Download, Eye, XCircle, Trash2 } 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 Modal from '@/components/ui/Modal';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { bookingsApi, apiClient } 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 [selectedBooking, setSelectedBooking] = useState<any>(null);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [bookingToDelete, setBookingToDelete] = useState<any>(null);
  const [successMessage, setSuccessMessage] = useState('');
  const [exportModalOpen, setExportModalOpen] = useState(false);
  const [exportDateFrom, setExportDateFrom] = useState('');
  const [exportDateTo, setExportDateTo] = useState('');
  const [exportColumns, setExportColumns] = useState<Record<string, boolean>>({
    bookingRef: true,
    passenger: true,
    status: true,
    bookingType: false,
    passengerCount: false,
    totalMinor: true,
    paymentStatus: true,
    createdAt: true,
  });

  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'] });
      setSuccessMessage('Booking cancelled successfully');
      setTimeout(() => setSuccessMessage(''), 3000);
    },
    onError: (error: any) => {
      alert(`Error: ${error.message || 'Failed to cancel booking'}`);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => apiClient.delete(`/bookings/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['bookings'] });
      setDeleteConfirmOpen(false);
      setBookingToDelete(null);
      setSuccessMessage('Booking deleted successfully');
      setTimeout(() => setSuccessMessage(''), 3000);
    },
    onError: (error: any) => {
      setDeleteConfirmOpen(false);
      alert(`Error: ${error.message || 'Failed to delete booking'}`);
    },
  });

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

  const handleDeleteClick = (booking: any) => {
    setBookingToDelete(booking);
    setDeleteConfirmOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (bookingToDelete) {
      await deleteMutation.mutateAsync(bookingToDelete.id);
    }
  };

  const confirmExport = () => {
    const cols = Object.entries(exportColumns).filter(([, v]) => v).map(([k]) => k);
    if (cols.length === 0) { alert('Please select at least one column'); return; }

    const exportItems = (data?.items || []).filter((b: any) => {
      if (!exportDateFrom && !exportDateTo) return true;
      const d = b.createdAt ? new Date(b.createdAt).toISOString().split('T')[0] : null;
      if (exportDateFrom && (!d || d < exportDateFrom)) return false;
      if (exportDateTo && (!d || d > exportDateTo)) return false;
      return true;
    });

    const csv = [
      cols.join(','),
      ...exportItems.map((booking: any) => {
        const values = cols.map(col => {
          switch (col) {
            case 'bookingRef': return booking.bookingRef;
            case 'passenger': return booking.passenger?.fullName || booking.contactEmail || 'Guest';
            case 'status': return booking.status;
            case 'bookingType': return booking.bookingType || 'N/A';
            case 'passengerCount': return booking.adultCount + booking.childCount;
            case 'totalMinor': return booking.totalMinor;
            case 'paymentStatus': return booking.paymentIntent?.status || 'PENDING';
            case 'createdAt': return booking.createdAt;
            default: return '';
          }
        });
        return values.map(v => `"${v}"`).join(',');
      }),
    ].join('\n');

    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `bookings-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    setExportModalOpen(false);
  };

  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: 'bookingType',
      label: 'Type',
      sortable: true,
      render: (booking: any) => booking.bookingType || 'ONE_WAY',
    },
    {
      key: 'passengerCount',
      label: 'Passengers',
      render: (booking: any) => {
        const adults = booking.adultCount || 0;
        const children = booking.childCount || 0;
        if (adults === 0 && children === 0) return '—';
        const parts = [`Adult: ${adults}`];
        if (children > 0) parts.push(`Child: ${children}`);
        return parts.join(' / ');
      },
    },
    {
      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 = [
    {
      label: 'View Details',
      onClick: (booking: any) => setSelectedBooking(booking),
      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',
    },
    {
      label: 'Delete',
      onClick: handleDeleteClick,
      variant: 'danger' as const,
      icon: Trash2,
    },
  ];

  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} onClick={() => setExportModalOpen(true)}>Export</ActionButton>
      </div>

      <div className="card">
        {successMessage && (
          <div className="mb-4 rounded-lg bg-green-50 dark:bg-green-900/20 p-4 text-sm text-green-800 dark:text-green-200">
            ✓ {successMessage}
          </div>
        )}
        {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>

      {/* Booking Details Modal */}
      <Modal isOpen={!!selectedBooking} onClose={() => setSelectedBooking(null)} title="Booking Details" size="xl">
        {selectedBooking && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium text-muted-foreground">Booking Reference</label>
                <p className="text-lg font-semibold font-mono">{selectedBooking.bookingRef}</p>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">Status</label>
                <div className="mt-1">
                  <Badge variant="status" status={selectedBooking.status}>{selectedBooking.status}</Badge>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">Booking Type</label>
                <p className="text-lg font-semibold">{selectedBooking.bookingType || 'N/A'}</p>
              </div>
              <div>
                <label className="text-sm font-medium text-muted-foreground">Created</label>
                <p className="text-lg font-semibold">{formatDateTime(selectedBooking.createdAt)}</p>
              </div>
            </div>

            <hr className="border-muted" />

            <div>
              <h3 className="text-lg font-semibold mb-3">Passenger Information</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Name</label>
                  <p className="text-lg font-semibold">{selectedBooking.passenger?.fullName || selectedBooking.contactEmail || 'N/A'}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Email</label>
                  <p className="text-lg font-semibold">{selectedBooking.contactEmail || selectedBooking.passenger?.email || 'N/A'}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Phone</label>
                  <p className="text-lg font-semibold">{selectedBooking.contactPhone || selectedBooking.passenger?.phone || 'N/A'}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Passenger ID</label>
                  <p className="text-sm font-mono">{selectedBooking.passengerId || 'N/A'}</p>
                </div>
              </div>
            </div>

            <hr className="border-muted" />

            <div>
              <h3 className="text-lg font-semibold mb-3">Journey Details</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Adults</label>
                  <p className="text-lg font-semibold">{selectedBooking.adultCount || 0}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Children</label>
                  <p className="text-lg font-semibold">{selectedBooking.childCount || 0}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Schedule ID</label>
                  <p className="text-sm font-mono">{selectedBooking.scheduleId || 'N/A'}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Promo Code</label>
                  <p className="text-lg font-semibold">{selectedBooking.promoCode || 'None'}</p>
                </div>
              </div>
            </div>

            <hr className="border-muted" />

            <div>
              <h3 className="text-lg font-semibold mb-3">Payment Information</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Amount</label>
                  <p className="text-lg font-semibold">{formatCurrency(selectedBooking.totalMinor, selectedBooking.currency)}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Payment Status</label>
                  <div className="mt-1">
                    <Badge variant="status" status={selectedBooking.paymentIntent?.status || 'PENDING'}>
                      {selectedBooking.paymentIntent?.status || 'PENDING'}
                    </Badge>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Paid At</label>
                  <p className="text-lg font-semibold">{selectedBooking.paidAt ? formatDateTime(selectedBooking.paidAt) : 'Not paid'}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Display Currency</label>
                  <p className="text-lg font-semibold">{selectedBooking.displayCurrency || selectedBooking.currency}</p>
                </div>
              </div>
            </div>

            <hr className="border-muted" />

            <div>
              <h3 className="text-lg font-semibold mb-3">Additional Information</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Source</label>
                  <p className="text-lg font-semibold">{selectedBooking.source || 'N/A'}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">Last Updated</label>
                  <p className="text-lg font-semibold">{formatDateTime(selectedBooking.updatedAt)}</p>
                </div>
              </div>
            </div>

            <div className="flex justify-end gap-2 pt-4">
              <ActionButton variant="secondary" onClick={() => setSelectedBooking(null)}>Close</ActionButton>
            </div>
          </div>
        )}
      </Modal>

      {/* Delete Confirmation Dialog */}
      <ConfirmDialog
        isOpen={deleteConfirmOpen}
        onClose={() => { setDeleteConfirmOpen(false); setBookingToDelete(null); }}
        onConfirm={handleConfirmDelete}
        title="Delete Booking"
        message={`Are you sure you want to permanently delete booking ${bookingToDelete?.bookingRef}? This action cannot be undone and will release all associated seats.`}
        confirmText="Delete"
        cancelText="Cancel"
        isLoading={deleteMutation.isPending}
        isDanger={true}
      />

      {/* Export Modal */}
      <Modal isOpen={exportModalOpen} onClose={() => setExportModalOpen(false)} title="Export Bookings" size="md">
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">Date From (Created)</label>
              <input type="date" className="input" value={exportDateFrom} onChange={(e) => setExportDateFrom(e.target.value)} />
            </div>
            <div>
              <label className="label">Date To (Created)</label>
              <input type="date" className="input" value={exportDateTo} onChange={(e) => setExportDateTo(e.target.value)} />
            </div>
          </div>

          <div>
            <p className="text-sm font-medium mb-2">Select Columns</p>
            <div className="space-y-2 max-h-56 overflow-y-auto">
              {[
                { key: 'bookingRef', label: 'Booking Reference' },
                { key: 'passenger', label: 'Passenger' },
                { key: 'status', label: 'Status' },
                { key: 'bookingType', label: 'Booking Type' },
                { key: 'passengerCount', label: 'Passenger Count' },
                { key: 'totalMinor', label: 'Amount' },
                { key: 'paymentStatus', label: 'Payment Status' },
                { key: 'createdAt', label: 'Created At' },
              ].map((col) => (
                <label key={col.key} className="flex items-center gap-3 p-2 hover:bg-gray-50 dark:hover:bg-gray-900/50 rounded cursor-pointer">
                  <input
                    type="checkbox"
                    checked={exportColumns[col.key] || false}
                    onChange={(e) => setExportColumns({ ...exportColumns, [col.key]: e.target.checked })}
                    className="w-4 h-4 rounded border-gray-300"
                  />
                  <span className="text-sm font-medium">{col.label}</span>
                </label>
              ))}
            </div>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <ActionButton variant="secondary" onClick={() => setExportModalOpen(false)}>Cancel</ActionButton>
            <ActionButton onClick={confirmExport}>Export CSV</ActionButton>
          </div>
        </div>
      </Modal>
    </div>
  );
}
