import { BackButton, Text, Textarea } from '@/components';
import AddressCard from '@/components/Cards/AddressCard';
import CustomModal from '@/components/CustomModal';
import UploadImager from '@/components/UploadImager';
import Button from '@/components/ui/Button';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useEffect, useState } from 'react';
import { Col, Row } from 'react-bootstrap';
import { useMediaQuery } from 'react-responsive';
import { useDispatch, useSelector } from 'react-redux';
import { setBookingDescription } from '@/lib/redux/slices/booking.slice';
import { RootState } from '@/lib/redux/store';
import { useCreateBookingMutation } from '@/lib/redux/services/user/booking.api';
import toast from 'react-hot-toast';
import { useSession } from 'next-auth/react';
import { start } from 'repl';

interface Contact {
  name: string;
  phone: string;
}

const WhatAreYouMoving: React.FC = () => {
  const dispatch = useDispatch();
  const router = useRouter();
  const isTablet = useMediaQuery({ query: '(max-width: 992px)' });
  const { data: session } = useSession();

  const bookingData = useSelector((state: RootState) => state.bookingJourney);
  const [description, setDescription] = useState<string>(bookingData?.description || '');
  const [contacts, setContacts] = useState<Contact[]>(
    bookingData?.additional_contacts?.length > 0
      ? bookingData.additional_contacts
      : [{ name: '', phone: '' }]
  );
  const [getEstimate, setGetEstimate] = useState<boolean>(false);

  const [createBooking, { isLoading }] = useCreateBookingMutation(); // 👈 RTK mutation hook

  useEffect(() => {
    const simpleLayout = document.getElementById('simple-layout');
    if (simpleLayout) {
      simpleLayout.classList.add('what-are-you-moving');
    }
  }, []);

  const handleGetEstimate = () => {
    dispatch(
      setBookingDescription({
        pickupLocation: bookingData.pick_up,
        destinationLocation: bookingData.drop_off,
        deliveryDate: bookingData.date,
        description: bookingData.description,
        additional_contacts: contacts,
      })
    );
    setGetEstimate(true);
  };

  const handleBookNow = async () => {
    const payload = {
      pick_up: {
        ...bookingData.pick_up,
        lat: String(bookingData.pick_up.lat), // Ensure lat is a string
        long: String(bookingData.pick_up.long), // Ensure long is a string
      },
      drop_off: {
        ...bookingData.drop_off,
        lat: String(bookingData.drop_off.lat), // Ensure lat is a string
        long: String(bookingData.drop_off.long), // Ensure long is a string
      },
      category: bookingData.category,
      vehicle_category: bookingData.vehicle_category,
      date: bookingData.date,
      time_slot: {
        start: bookingData.time_slot?.start || "",
        end: bookingData.time_slot?.end || "",
      },
      description: description,
      est_fare: bookingData.est_fare || '100',
      additional_contacts: contacts.length > 0
        ? {
          name: contacts[0].name,
          phone_number: contacts[0].phone,
        }
        : { name: '', phone_number: '' },
    };


    try {
      const token = session?.user?.token
      console.log(token, "token");
      if (!token) {
        toast.error('Token not found. Please try again.');
        return;
      } const res = await createBooking({
        body: payload,
        token,
      }).unwrap();
      router.push('/user');
    } catch (error) {
      console.error('Booking failed:', error.message);
      toast(error.data.message);
    }
  };

  const addContact = () => setContacts([...contacts, { name: '', phone: '' }]);
  const handleRemoveContact = (index: number) =>
    setContacts(contacts.filter((_, i) => i !== index));

  return (
    <>
      <Head>
        <title>What Are you Moving | Deliver X</title>
      </Head>
      <div>
        <h2 className="display-6 d-flex justify-content-center align-items-center fw-bolder text-center">
          {isTablet && <BackButton />} What are you moving?
        </h2>

        <Row className="w-100 mt-sm-6 mt-3 justify-content-center">
          <Col md={12}>
            <Row className="gx-5 gy-3">
              <Col lg={7}>
                <h2 className=" fs-12 fs-sm-14 fw-bold">Description</h2>
                <Textarea
                  name="description"
                  rows={4}
                  placeholder="Tell us what you are moving or share special instructions."
                  className="form-control mb-3 rounded-4 shadow-none"
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                />

                <UploadImager />

                <Text size="24px" tag="h2" className="mt-3 pb-0 mb-0" marginBottom="10px" weight="bold">
                  Additional Contact
                </Text>
                <Text color="#777" marginBottom="10px" >
                  They’ll receive updates about the status of your Delivery.
                </Text>

                {contacts.map((contact, index) => (
                  <div
                    key={index}
                    className="d-flex mb-2 justify-content-between align-items-center gap-3"
                  >
                    <input
                      type="text"
                      placeholder="Name"
                      value={contact.name}
                      onChange={(e) => {
                        const updated = [...contacts];
                        if (updated[index]) {
                          updated[index] = {
                            ...updated[index],
                            name: e.target.value,
                          };
                          setContacts(updated);
                        }
                      }}
                      className="form-control shadow-none"
                    />
                    <input
                      type="text"
                      placeholder="Phone Number"
                      value={contact.phone}
                      onChange={(e) => {
                        const updated = [...contacts];
                        if (updated[index]) {
                          updated[index] = {
                            ...updated[index],
                            phone: e.target.value,
                          };
                          setContacts(updated);
                        }
                      }}
                      className="form-control shadow-none"
                    />
                    {contacts.length > 1 && (
                      <button
                        onClick={() => handleRemoveContact(index)}
                        className="btn btn-sm btn-outline-danger"
                      >
                        &times;
                      </button>
                    )}
                  </div>
                ))}
                <Link
                  href="#!"
                  className="mt-3 text-decoration-underline text-primary-color"
                  onClick={addContact}
                >
                  + Add another contact
                </Link>

                <Button
                  size="md"
                  onClick={handleGetEstimate}
                  className="d-block UrbanistRegular btn btn-feature mx-auto mt-3 py-2 mb-3 mb-sm-0"
                >
                  Get Estimate
                </Button>
              </Col>

              <Col lg={5}>
                <AddressCard />
              </Col>
            </Row>
          </Col>
        </Row>
      </div>

      <CustomModal
        isCloseBtn
        size="lg"
        show={getEstimate}
        handleClose={() => setGetEstimate(false)}
      >
        <div className="d-flex flex-column px-sm-5 py-4 justify-content-center align-items-center">
          <h5 className="fw-bold modal-title position-relative">ESTIMATE</h5>

          <ul className="list-group w-100">
            <li className="list-group-item">
              <h6 className="text-light-grey-2 fs-10 mb-0">Pickup</h6>
              <h5 className="mb-0 pb-0 fs-sm-12 fs-11 fw-bold">
                {bookingData?.pick_up?.address || 'Pickup address not available'}
              </h5>
            </li>
            <li className="list-group-item">
              <h6 className="text-light-grey-2 fs-10 mb-0">Destination</h6>
              <h5 className="mb-0 pb-0 fs-sm-12 fs-11 fw-bold">
                {bookingData?.drop_off?.address || 'Drop off address not available'}
              </h5>
            </li>
            <li className="list-group-item">
              <h6 className="text-light-grey-2 fs-10 mb-0">Time of Delivery</h6>
              <h5 className="mb-0 pb-0 fs-sm-12 fs-11 fw-bold">
                {bookingData?.date || 'N/A'}
              </h5>
            </li>
            <li className="list-group-item">
              <h6 className="text-light-grey-2 fs-10 mb-0">Labor per min</h6>
              <h5 className="mb-0 pb-0 fs-sm-12 fs-11 fw-bold">$45.02</h5>
            </li>
            <li className="list-group-item">
              <h5 className="text-dark fs-10 mb-0">Estimated Delivery Charges</h5>
              <h5 className="mb-0 pb-0 fs-sm-12 text-primary-color fs-11 fw-bold">
                ${bookingData?.est_fare || '45.02'}
              </h5>
            </li>
          </ul>

          <Button
            size="lg"
            disabled={isLoading}
            onClick={handleBookNow}
            className="btn btn-feature UrbanistRegular py-2 mt-4 mx-auto"
          >
            {isLoading ? 'Booking...' : 'Book Now'}
          </Button>
        </div>
      </CustomModal>
    </>
  );
};

export default WhatAreYouMoving;
