"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import StepSelectStore from "./StepSelectorStore";
import StepEnterDetails from "./StepEnterDetails";
import StepConfirmation from "./StepConfirmation";
import StepBookSlot from "./StepBookSlot";
import { apiCall } from "@/utils/callApi";
import useAuth from "@/hooks/useAuth";
import { toast } from "sonner";

export interface SelectedStore {
  _id: string;
  name: string;
  address: string;
  city: string;
  state: string;
  phone: string;
  openTime: string;
  closeTime: string;
}

export interface SelectedSlot {
  date: string;
  slotPeriod: "morning" | "afternoon" | "evening";
  timeSlot: string;
}

export interface UserDetails {
  name: string;
  phone: string;
  email: string;
  celebrating: "groom" | "bride" | "event" | "other";
  lookingFor: string;
}

const STEPS = [
  { id: 1, label: "Select Store" },
  { id: 2, label: "Book a Slot" },
  { id: 3, label: "Enter Details" },
];

export default function AppointmentPage() {
  const router = useRouter();
  const { clienttoken } = useAuth();
  const [stores, setStores] = useState<any[]>([]);
  const [step, setStep] = useState(1);

  const [selectedStore, setSelectedStore] = useState<any>(null);
  const [selectedSlot, setSelectedSlot] = useState<any>(null);

  const fetchStores = async () => {
    try {
      const res: any = await apiCall<any[]>("/clientapi/appointment", {
        headers: {
          Authorization: `Bearer ${clienttoken}`,
        },
      });

      if (res.data?.success) {
        setStores(res.data?.data || []);
      }
    } catch (error) {}
  };
  const handleSubmit = async (details: any) => {
    try {
      if (
        !details?.name?.trim() ||
        !details?.email?.trim() ||
        !details?.phone?.trim() ||
        !details?.lookingFor.trim()
      ) {
        toast.error("Please fill all details");
        return;
      }
      const res = await fetch("/api/appointments", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${clienttoken}`,
        },
        body: JSON.stringify({
          storeId: selectedStore._id,
          storeName: selectedStore.name,

          date: selectedSlot.date,
          timeSlot: selectedSlot.timeSlot,
          slotPeriod: selectedSlot.slotPeriod,

          name: details.name,
          phone: details.phone,
          email: details.email,
          celebrating: details.celebrating,
          lookingFor: details.lookingFor,
        }),
      });

      const data = await res.json();

      if (data.success) {
        toast.success("Appointment booked successfully!");
        // console.log("Appointment ID:", data.data._id);
        router.push("/thankingyou");
      } else {
        console.error("Error", data);
        toast.error(data?.error);
      }
    } catch (error: any) {
      console.error("Error", error);
      toast.error(
        error?.data?.message || error.message || "Something went wrong",
      );
      alert("Something went wrong");
    }
  };

  useEffect(() => {
    fetchStores();
  }, []);

  return (
    <section className="appointmentcontainer py-8 pt-4 md:py-12 md:pt-12">
      <div className="container px-3">
        {/* HEADER */}
        <div className="section-heading text-center">
          <h2>BOOK AN APPOINTMENT</h2>
        </div>

        {/* MAIN LAYOUT */}
        <div className="-mx-3 flex flex-wrap justify-center xl:-mx-4 2xl:-mx-6">
          {/* LEFT STEP PER */}
          <div className="mb-lg-0 mb-6 w-full px-3 sm:w-full md:w-6/12 lg:w-5/12 xl:w-4/12 xl:px-4 2xl:w-4/12 2xl:px-6">
            <div className="flex h-full flex-col rounded-xl border border-[rgba(var(--primary),0.3)] bg-white p-6 md:p-10">
              {/* STEP 1 */}
              <div className="flex items-start gap-4">
                <div className="flex flex-col items-center">
                  <div
                    className={`z-10 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full border text-sm md:text-base xl:text-lg 2xl:h-14 2xl:w-14 ${
                      step === 1
                        ? "border-primary bg-primary text-white"
                        : selectedStore
                          ? "border-green-500 bg-green-500 text-white"
                          : "border-gray-300 text-gray-400"
                    }`}
                  >
                    {selectedStore && step === 1 ? "✓" : "1"}
                  </div>
                  {/* line below circle 1 */}
                  <div className="mt-1 h-6 w-[2px] bg-gray-200 md:h-10" />
                </div>
                <div className="flex-1 pt-3">
                  <div className="flex items-center justify-between">
                    <p
                      className={`text-sm font-semibold md:text-base 2xl:text-lg ${step === 1 ? "text-primary" : ""}`}
                    >
                      {selectedStore?.name ?? "Pick a location"}
                    </p>
                    {selectedStore && (
                      <button
                        onClick={() => {
                          setStep(1);
                          setSelectedStore(null);
                        }}
                        className="text-xs text-[rgba(var(--primary),1)] hover:underline md:text-sm 2xl:text-base"
                      >
                        Edit
                      </button>
                    )}
                  </div>
                  {selectedStore && (
                    <p className="text-xs text-gray-500 md:text-sm 2xl:text-base">
                      {selectedStore.name}
                    </p>
                  )}
                </div>
              </div>

              {/* STEP 2 */}
              <div className="flex items-start gap-4">
                <div className="flex flex-col items-center">
                  <div
                    className={`z-10 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full border text-sm md:text-base xl:text-lg 2xl:h-14 2xl:w-14 ${
                      step === 2
                        ? "border-[rgba(var(--primary),1)] bg-[rgba(var(--primary),1)] text-white"
                        : selectedSlot && step !== 1
                          ? "border-green-500 bg-green-500 text-white"
                          : "border-gray-300 text-gray-400"
                    }`}
                  >
                    {selectedSlot && step === 2 ? "✓" : "2"}
                  </div>
                  {/* line below circle 2 */}
                  <div className="mt-1 h-6 w-[2px] bg-gray-200 md:h-10" />
                </div>
                <div className="flex-1 pt-3">
                  <div className="flex items-center justify-between">
                    <p
                      className={`text-sm font-semibold md:text-base 2xl:text-lg ${step === 2 ? "text-[rgba(var(--primary),1)]" : ""}`}
                    >
                      Book a slot
                    </p>
                    {selectedSlot && step === 3 && (
                      <button
                        onClick={() => {
                          setStep(2);
                          setSelectedSlot(null);
                        }}
                        className="text-xs text-[rgba(var(--primary),1)] hover:underline md:text-sm 2xl:text-base"
                      >
                        Edit
                      </button>
                    )}
                  </div>
                  {selectedSlot && (
                    <p className="text-xs text-gray-500 md:text-sm 2xl:text-base">
                      {selectedSlot.date} • {selectedSlot.timeSlot}
                    </p>
                  )}
                </div>
              </div>

              {/* STEP 3 — no line below */}
              <div className="flex items-start gap-4">
                <div className="flex flex-col items-center">
                  <div
                    className={`z-10 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full border text-sm md:text-base xl:text-lg 2xl:h-14 2xl:w-14 ${step === 3 ? "border-[rgba(var(--primary),1)] bg-[rgba(var(--primary),1)] text-white" : "border-gray-300 text-gray-400"}`}
                  >
                    3
                  </div>
                </div>
                <div className="flex-1 pt-3">
                  <p
                    className={`text-sm font-semibold md:text-base 2xl:text-lg ${step === 3 ? "text-[rgba(var(--primary),1)]" : ""}`}
                  >
                    Enter details
                  </p>
                  {step === 3 && (
                    <p className="text-xs text-gray-500 md:text-sm 2xl:text-base">
                      Final step
                    </p>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* RIGHT CONTENT (DYNAMIC PANEL) */}
          <div className="mb-lg-0 mb-6 w-full px-3 sm:w-full md:w-6/12 lg:w-7/12 xl:w-7/12 xl:px-4 2xl:w-7/12 2xl:px-6">
            {step === 1 && (
              <StepSelectStore
                stores={stores}
                onSelect={(store) => {
                  setSelectedStore(store);
                  setStep(2);
                }}
              />
            )}

            {step === 2 && selectedStore && (
              <StepBookSlot
                selectedStore={selectedStore}
                selectedSlot={selectedSlot}
                onSelect={(slot) => {
                  setSelectedSlot(slot);
                  setStep(3);
                }}
                onEditStore={() => {
                  setSelectedStore(null);
                  setStep(1);
                }}
              />
            )}

            {step === 3 && selectedStore && selectedSlot && (
              <StepEnterDetails
                selectedStore={selectedStore}
                selectedSlot={selectedSlot}
                onSubmit={(details) => {
                  handleSubmit(details);
                }}
                onEditStore={() => {
                  setStep(1);
                }}
                onEditSlot={() => {
                  setStep(2);
                }}
              />
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
