"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/app/shadcn_components/ui/button";
import { Input } from "@/app/shadcn_components/ui/input";
import { Checkbox } from "@/app/shadcn_components/ui/checkbox";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
} from "@/app/shadcn_components/ui/select";
import { Fragment } from "react";
import { useOnboardUser } from "./OnboardUserHook";

const referralLabels: Record<string, string> = {
  search: "Search engine (e.g. Google)",
  social_media: "Social media",
  NRLA: "NRLA (National Residential Landlords Association)",
  partner: "Through a partner organisation",
  word_of_mouth: "Word of mouth",
  other: "Other",
};

const OnboardingSchema = z
  .object({
    firstName: z.string().min(1, "First name is required"),
    lastName: z.string().min(1, "Last name is required"),
    userType: z.enum(
      [
        "private_landlord",
        "private_tenant",
        "social_landlord",
        "social_tenant",
        "homeowner",
        "other",
      ],
      { required_error: "Please tell us who you are" }
    ),
    propertyCount: z
      .enum(
        [
          "1",
          "2–5",
          "6–20",
          "21+",
          "1–50",
          "51–100",
          "101–300",
          "301–1000",
          "1000+",
        ],
        {
          required_error:
            "Please tell us how many homes you’re responsible for",
        }
      )
      .optional(),
    goals: z
      .array(
        z.enum([
          "access_funding",
          "net_zero",
          "improve_condition",
          "save_money",
          "other",
        ])
      )
      .min(1, "Please select at least one goal"),
    referralSource: z.enum(
      ["search", "social_media", "NRLA", "partner", "word_of_mouth", "other"],
      { required_error: "Please tell us how you heard about Domna" }
    ),
    nrlaMembershipId: z.string().optional(),
    acceptedPrivacy: z.boolean().refine((v) => v === true, {
      message: "You must accept our privacy policy to continue",
    }),
    marketingOptIn: z.boolean().optional(), // only optional field
  })
  .refine(
    (data) => {
      const isLandlord =
        data.userType === "private_landlord" ||
        data.userType === "social_landlord";
      if (isLandlord && !data.propertyCount) return false;
      return true;
    },
    {
      message: "Please tell us how many homes you’re responsible for",
      path: ["propertyCount"],
    }
  );

type OnboardingData = z.infer<typeof OnboardingSchema>;

export default function OnboardingPage() {
  const router = useRouter();
  const [step, setStep] = useState(1);

  const form = useForm<OnboardingData>({
    resolver: zodResolver(OnboardingSchema),
    defaultValues: {
      goals: [],
      marketingOptIn: false,
      acceptedPrivacy: false,
    },
    mode: "onChange",
  });

  const {
    register,
    handleSubmit,
    control,
    watch,
    setValue,
    trigger,
    formState: { errors, isValid },
  } = form;

  const userType = watch("userType");
  const referralSource = watch("referralSource");
  const onboardMutation = useOnboardUser();

  async function onSubmit(data: OnboardingData) {
    onboardMutation.mutate(data);
  }

  async function nextStep() {
    let valid = false;

    if (step === 1) {
      // Validate step 1 fields only
      const ok = await trigger(["userType", "propertyCount"], {
        shouldFocus: true,
      });
      const values = form.getValues();

      const isLandlord =
        values.userType === "private_landlord" ||
        values.userType === "social_landlord";

      if (isLandlord && !values.propertyCount) {
        form.setError("propertyCount", {
          type: "manual",
          message: "Please tell us how many homes you’re responsible for",
        });
        valid = false;
      } else {
        valid = ok;
      }
    } else if (step === 2) {
      valid = await trigger(["goals", "referralSource"], { shouldFocus: true });
    } else {
      valid = true;
    }

    if (valid) setStep((s) => Math.min(s + 1, 3));
  }

  function prevStep() {
    setStep((s) => Math.max(s - 1, 1));
  }

  return (
    <div className="flex bg-gray-50">
      {/* Left image panel */}
      <div className="hidden md:flex w-1/2 relative overflow-hidden">
        <div
          className="absolute inset-0 bg-cover bg-center"
          style={{ backgroundImage: "url('/images/Alexandra-Road-Park.webp')" }}
        ></div>

        <div className="relative z-10 flex items-start justify-start w-full h-full">
          <div className="mt-20 p-20 text-gray-100 shadow-xl w-[75%] rounded-br-[8rem] bg-gradient-to-r from-brandblue to-midblue">
            <h2 className="text-5xl font-bold mb-4">Welcome to Ara</h2>
            <p className="text-xl leading-relaxed text-brandbrown">
              Help us get to know you so we can tailor your experience.
            </p>
          </div>
        </div>
      </div>

      {/* Right section with journey and form */}
      <div className="flex flex-col flex-1 items-center justify-start p-10 relative">
        {/* Domna Journey Progress */}
        <div className="w-full max-w-3xl mt-8 mb-8">
          <h3 className="text-center text-brandblue text-xl font-semibold mb-5">
            Your retrofit journey with Domna
          </h3>

          {/* Row 1: Nodes + Connectors */}
          <div className="relative flex items-center justify-center w-full">
            {[
              { label: "Remote Portfolio Assessment", icon: "🧠", step: 1 },
              { label: "Survey & Design", icon: "📐", step: 2 },
              { label: "Installation & Funding Claim", icon: "🏡", step: 3 },
            ].map((stage, i, arr) => {
              const active = step >= stage.step;
              const showConnector = i < arr.length - 1;
              const segmentFilled = step > stage.step;

              return (
                <Fragment key={stage.step}>
                  <div className="flex-none w-[180px] flex flex-col items-center text-center">
                    <div
                      className={`flex items-center justify-center w-12 h-12 rounded-full border-2 text-lg font-semibold mb-2 transition-all duration-500 ${
                        active
                          ? "bg-brandblue text-white border-brandblue shadow-md"
                          : "bg-white text-gray-400 border-gray-300"
                      }`}
                    >
                      <span>{stage.icon}</span>
                    </div>
                    <p
                      className={`text-sm font-medium max-w-[8rem] ${
                        active ? "text-brandblue" : "text-gray-400"
                      }`}
                    >
                      {stage.label}
                    </p>
                  </div>

                  {showConnector && (
                    <div className="flex-none w-[60px] md:w-[80px] relative">
                      <div className="absolute left-2 right-2 top-[1.5rem] h-[2px] bg-gray-300" />
                      <div
                        className={`absolute left-2 top-[1.5rem] h-[2px] transition-all duration-500 ${
                          segmentFilled
                            ? "right-2 bg-brandblue"
                            : "w-0 bg-brandblue"
                        }`}
                      />
                    </div>
                  )}
                </Fragment>
              );
            })}
          </div>
          {/* Row 2: Captions aligned under each node */}
          <div className="mt-4 grid grid-cols-3 gap-2 text-gray-600 justify-items-center">
            {[
              {
                step: 1,
                caption:
                  "IQ models home energy improvements, costs, and funding availability at the click of a button.",
              },
              {
                step: 2,
                caption:
                  "Schedule a survey. Our team surveys properties and produces a tailored retrofit design.",
              },
              {
                step: 3,
                caption:
                  "We guide installation and help you claim any available funding to complete your retrofit journey.",
              },
            ].map(({ step: s, caption }) => (
              <div
                key={s}
                className={`text-xs leading-snug text-center w-[200px] transition-opacity duration-300 ${
                  step === s ? "opacity-100" : "opacity-70"
                }`}
                style={{ minHeight: "3rem" }}
              >
                {caption}
              </div>
            ))}
          </div>
        </div>

        {/* Onboarding Form */}
        <form
          onSubmit={handleSubmit(onSubmit, (errors) => {
            console.log("Validation errors:", errors);
          })}
          className="w-full max-w-lg bg-white rounded-xl shadow-md p-8 flex flex-col min-h-[450px]"
        >
          {/* Progress indicator */}
          <div className="flex items-center pb-4">
            {[1, 2, 3].map((i) => (
              <div
                key={i}
                className={`flex-1 h-1 mx-1 rounded ${
                  i <= step ? "bg-brandbrown" : "bg-gray-200"
                }`}
              />
            ))}
          </div>

          <div className="flex-grow space-y-6">
            {step === 1 && (
              <div className="space-y-4">
                <h1 className="text-xl font-semibold text-brandblue">
                  Step 1 of 3
                </h1>
                <p className="text-sm font-medium text-gray-700">
                  {`By telling us a bit about yourself, we'll know how to best support your journey.`}
                </p>
                <Controller
                  control={control}
                  name="userType"
                  render={({ field }) => (
                    <Select
                      value={field.value}
                      onValueChange={(value) => {
                        field.onChange(value);
                        setValue("propertyCount", undefined); // ✅ clear previous selection
                      }}
                    >
                      <SelectTrigger>
                        {field.value
                          ? field.value
                              .replace("_", " ")
                              .replace(/\b\w/g, (c) => c.toUpperCase())
                          : "Tell us who you are"}
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="private_landlord">
                          I’m a private landlord
                        </SelectItem>
                        <SelectItem value="private_tenant">
                          I’m a private tenant
                        </SelectItem>
                        <SelectItem value="social_landlord">
                          I manage social housing
                        </SelectItem>
                        <SelectItem value="social_tenant">
                          I live in social housing
                        </SelectItem>
                        <SelectItem value="homeowner">
                          I own my own home
                        </SelectItem>
                        <SelectItem value="other">Something else</SelectItem>
                      </SelectContent>
                    </Select>
                  )}
                />

                {errors.userType && (
                  <p className="text-sm text-red-500">
                    {errors.userType.message}
                  </p>
                )}

                {(userType === "private_landlord" ||
                  userType === "social_landlord") && (
                  <Controller
                    control={control}
                    name="propertyCount"
                    render={({ field }) => (
                      <Select
                        value={field.value}
                        onValueChange={field.onChange}
                      >
                        <SelectTrigger>
                          {field.value ??
                            "Please tell us how many properties you're responsible for"}
                        </SelectTrigger>
                        <SelectContent>
                          {userType === "private_landlord" ? (
                            <>
                              <SelectItem value="1">1</SelectItem>
                              <SelectItem value="2–5">2–5</SelectItem>
                              <SelectItem value="6–20">6–20</SelectItem>
                              <SelectItem value="21+">21+</SelectItem>
                            </>
                          ) : (
                            <>
                              <SelectItem value="1–50">1–50</SelectItem>
                              <SelectItem value="51–100">51–100</SelectItem>
                              <SelectItem value="101–300">101–300</SelectItem>
                              <SelectItem value="301–1000">301–1000</SelectItem>
                              <SelectItem value="1000+">1000+</SelectItem>
                            </>
                          )}
                        </SelectContent>
                      </Select>
                    )}
                  />
                )}
              </div>
            )}

            {errors.propertyCount && (
              <p className="text-sm text-red-500">
                {errors.propertyCount.message}
              </p>
            )}

            {step === 2 && (
              <div className="space-y-4">
                <h1 className="text-2xl font-semibold text-brandblue">
                  Step 2 of 3
                </h1>

                {/* Goals section */}
                <p className="font-medium text-gray-700">
                  What would you like to achieve with Domna?
                  <span className="text-red-500">*</span>
                </p>
                <div className="grid grid-cols-2 gap-2">
                  {(
                    [
                      "access_funding",
                      "net_zero",
                      "improve_condition",
                      "save_money",
                      "other",
                    ] as OnboardingData["goals"]
                  ).map((g) => (
                    <label
                      key={g}
                      className="flex items-center space-x-2 cursor-pointer"
                    >
                      <Checkbox
                        checked={watch("goals")?.includes(g)}
                        onCheckedChange={(checked) => {
                          const goals = (watch("goals") ??
                            []) as OnboardingData["goals"];
                          setValue(
                            "goals",
                            checked
                              ? [...goals, g]
                              : goals.filter((gg) => gg !== g),
                            { shouldValidate: true } // ✅ triggers live validation feedback
                          );
                        }}
                      />
                      <span className="capitalize text-sm">
                        {g.replace("_", " ")}
                      </span>
                    </label>
                  ))}
                </div>
                {errors.goals && (
                  <p className="text-sm text-red-500">{errors.goals.message}</p>
                )}

                {/* Referral source section */}
                <Controller
                  control={control}
                  name="referralSource"
                  render={({ field }) => (
                    <Select
                      value={field.value}
                      onValueChange={(value) => {
                        field.onChange(value);
                        trigger("referralSource"); // update validation instantly
                      }}
                    >
                      <SelectTrigger>
                        {field.value
                          ? referralLabels[field.value]
                          : "How did you hear about us?"}
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="search">
                          Search engine (e.g. Google)
                        </SelectItem>
                        <SelectItem value="social_media">
                          Social media
                        </SelectItem>
                        <SelectItem value="NRLA">
                          NRLA (National Residential Landlords Association)
                        </SelectItem>
                        <SelectItem value="partner">
                          Through a partner organisation
                        </SelectItem>
                        <SelectItem value="word_of_mouth">
                          Word of mouth
                        </SelectItem>
                        <SelectItem value="other">Other</SelectItem>
                      </SelectContent>
                    </Select>
                  )}
                />
                {errors.referralSource && (
                  <p className="text-sm text-red-500">
                    {errors.referralSource.message}
                  </p>
                )}

                {referralSource === "NRLA" && (
                  <div>
                    <label className="flex items-center space-x-2 text-xs text-gray-700 mb-1">
                      {`You don't need to enter your NRLA membership ID but you may be eligible for additional discounts`}
                    </label>
                    <Input
                      {...register("nrlaMembershipId")}
                      placeholder="Enter your NRLA membership ID"
                    />
                  </div>
                )}
              </div>
            )}

            {step === 3 && (
              <div className="space-y-4">
                <h1 className="text-xl font-semibold text-brandblue">
                  Step 3 of 3
                </h1>
                <Input
                  {...register("firstName")}
                  placeholder="First name"
                  required
                />
                <Input
                  {...register("lastName")}
                  placeholder="Last name"
                  required
                />

                <label className="flex items-center space-x-2">
                  <Controller
                    name="acceptedPrivacy"
                    control={control}
                    render={({ field }) => (
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={(checked) =>
                          field.onChange(checked === true)
                        }
                      />
                    )}
                  />
                  <span className="text-sm">
                    I agree to the{" "}
                    <a
                      href="https://www.domna.homes/privacy"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-brandblue underline"
                    >
                      Privacy Policy
                    </a>
                  </span>
                </label>

                {errors.acceptedPrivacy && (
                  <p className="text-sm text-red-500">
                    {errors.acceptedPrivacy.message}
                  </p>
                )}

                <label className="flex items-center space-x-2">
                  <Controller
                    name="marketingOptIn"
                    control={control}
                    render={({ field }) => (
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={(checked) =>
                          field.onChange(checked === true)
                        }
                      />
                    )}
                  />

                  <span className="text-sm text-gray-700">
                    I’d like to hear more about funding opportunities, retrofit
                    schemes, and energy upgrades.
                  </span>
                </label>
              </div>
            )}
          </div>

          {/* Buttons fixed at bottom */}
          <div className="flex justify-end pt-4">
            {step > 1 && (
              <Button
                className="bg-brandlightblue mr-2"
                variant="outline"
                type="button"
                onClick={prevStep}
              >
                Back
              </Button>
            )}
            {step < 3 ? (
              <Button
                type="button"
                className="bg-brandbrown hover:bg-hoverblue"
                onClick={nextStep}
              >
                Next
              </Button>
            ) : (
              <Button
                type="submit"
                className="bg-brandbrown hover:bg-hoverblue flex items-center justify-center"
                disabled={onboardMutation.isPending}
              >
                {onboardMutation.isPending ? "Finishing..." : "Finish"}
              </Button>
            )}
            {onboardMutation.isError && (
              <p className="text-sm text-red-500 mt-2">
                {(onboardMutation.error as Error).message}
              </p>
            )}
          </div>
        </form>
      </div>
    </div>
  );
}
