import { Text } from '@/components';
import StatusBox from '@/components/StatusBox';
import Table from '@/components/Table';
import PageHeader from '@/components/ui/PageHeader';
import Head from 'next/head';
import Link from 'next/link';
import { useState } from 'react';
import { Tab, TabList, TabPanel, Tabs } from 'react-tabs';
import { useSelector } from 'react-redux';
import { useGetAllRidesQuery } from '@/lib/redux/services/user/booking.api';
import { Spinner } from 'react-bootstrap';

interface Booking {
  _id: string;
  date: string;
  status: string;
  price: number;
  description: string;
  category: string;
  vehicle_category: string;
  pick_up: { address: string; lat: number; long: number; _id: string };
  drop_off: { address: string; lat: number; long: number; _id: string };
  additional_contacts: { name: string; phone_number: string; _id: string }[];
  time_slot: { start: string; end: string; _id: string };
  is_paid: boolean;
  upload_image: string[];
}

const BookingOverview = () => {
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const token = useSelector((state: any) => state?.auth?.token);

  const { data, isLoading } = useGetAllRidesQuery({
    status: selectedStatus === 'all' ? 'all' : selectedStatus,
    token,
  }, { refetchOnMountOrArgChange: true, refetchOnFocus: true });

  const bookings: Booking[] = data?.data || [];

  const columns = [
    {
      name: 'S.no',
      selector: (row: Booking, index: number) => <Text>{index + 1}</Text>,
      sortable: true,
    },
    {
      name: 'Description',
      selector: (row: Booking) => (
        <Text className="mb-0 pb-0">{row?.description?.slice(0, 30)}...</Text>
      ),
      sortable: true,
    },
    {
      name: 'Date',
      selector: (row: Booking) => (
        <Text className="mb-0 pb-0">{new Date(row?.date).toLocaleDateString()}</Text>
      ),
      sortable: true,
    },
    {
      name: 'Pick-Up Address',
      selector: (row: Booking) => (
        <Text className="mb-0 pb-0">{row?.pick_up?.address}</Text>
      ),
      sortable: true,
    },
    {
      name: 'Drop-Off Address',
      selector: (row: Booking) => (
        <Text className="mb-0 pb-0">{row?.drop_off?.address}</Text>
      ),
      sortable: true,
    },
    {
      name: 'Status',
      selector: (row: Booking) => {
        let statusStyle = {};
        const displayStatus = row?.status === 'accepted' ? 'in-progress' : row?.status;

        switch (displayStatus) {
          case 'requested':
            statusStyle = { color: '#7A49FF', background: '#F4F0FF' };
            break;
          case 'completed':
            statusStyle = { color: '#00BF60', background: '#E6FAF2' };
            break;
          case 'in-progress':
            statusStyle = { color: '#42AEE0', background: 'rgba(66, 174, 224, 0.2)' };
            break;
          case 'cancelled':
            statusStyle = { color: '#D90000', background: 'rgba(255, 154, 154, 0.20)' };
            break;
          default:
            statusStyle = {};
        }

        return <StatusBox style={statusStyle} title={displayStatus} />;
      },
      sortable: true,
    },
    {
      name: 'Charges',
      selector: (row: Booking) => (
        <div className="d-flex justify-content-center align-items-center gap-2">
          <img src="/images/icons/charge-icon.svg" alt="" />
          <Text className="mb-0 pb-0">${row?.price?.toFixed(2)}</Text>
        </div>
      ),
      sortable: true,
    },
    {
      name: 'Action',
      selector: (row: Booking) => {
        const displayStatus = row?.status === 'accepted' ? 'in-progress' : row?.status;
        const link = `/carrier/booking-management/${displayStatus}?id=${row._id}`;
        return (
          <Link href={link} legacyBehavior>
            <a className="cursor-pointer">
              <img src="/images/icons/eye-icon.svg" alt="View" />
            </a>
          </Link>
        );
      },
      sortable: false,
    },
  ];

  const customStyles = {
    rows: {
      style: {
        paddingTop: '10px',
        paddingBottom: '10px',
      },
    },
    headCells: {
      style: {
        padding: '10px',
      },
    },
    cells: {
      style: {
        padding: '10px',
      },
    },
  };

  const statuses = ['all', 'requested', 'accepted', 'cancelled', 'completed'];
  const tabLabels = ['All', 'Requested', 'In-progress', 'Cancelled', 'Completed'];

  return (
    <>
      <Head>
        <title>Booking Overview</title>
      </Head>

      <div className="mt-2 mb-3">
        <PageHeader title="Booking Overview" />
      </div>

      <Tabs selectedIndex={statuses.indexOf(selectedStatus)} onSelect={(index) => setSelectedStatus(statuses[index])}>
        <TabList>
          {tabLabels.map((label, i) => (
            <Tab key={i}>{label}</Tab>
          ))}
        </TabList>

        {statuses.map((status) => (
          <TabPanel key={status}>
            <div>
              {isLoading ? (
                <div className="d-flex justify-content-center align-items-center py-5">
                  <Spinner animation="border" role="status" variant="primary">
                    <span className="visually-hidden">Loading...</span>
                  </Spinner>
                </div>
              ) : (
                <Table
                  // @ts-ignore
                  columns={columns}
                  data={bookings}
                  customStyles={customStyles}
                  progressPending={false}
                />
              )}
            </div>
          </TabPanel>
        ))}
      </Tabs>
    </>
  );
};

export default BookingOverview;
