"use client";

import { useState, useMemo } from "react";
import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Play } from "lucide-react";

import {
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from "@/app/shadcn_components/ui/form";

import { Card } from "@/app/shadcn_components/ui/card";
import { Input } from "@/app/shadcn_components/ui/input";
import { Button } from "@/app/shadcn_components/ui/button";
import {
  SelectScenarioDropdown,
  SelectDropdown,
  ScenarioOption,
} from "@/app/portfolio/[slug]/components/RemoteAssessmentDropdowns";
import MeasuresCheckboxes from "@/app/portfolio/[slug]/components/MeasuresCheckboxes";
import { measuresList } from "@/app/db/schema/recommendations";
import { ScenarioSelect } from "@/app/db/schema/recommendations";
import {
  RemoteAssessmentFormSchema,
  type RemoteAssessmentFormValues,
} from "@/app/portfolio/[slug]/components/FormSchema";

const housingTypeOptions = [
  { label: "Social", value: "Social" },
  { label: "Private", value: "Private" },
];

// -------------------
// Component
// -------------------
export default function ScenarioSetup({
  portfolioId,
  scenarios,
  disabled = false,
  selectedAddress,
  selectedPostcode,
  selectedUprn,
  selectedPropertyType,
  selectedBuiltForm,
  isSubmitting,
  onSubmitRemoteAssessment,
  setSelectedScenario,
  selectedScenario,
}: {
  portfolioId: string;
  scenarios: ScenarioSelect[];
  disabled?: boolean;
  selectedAddress: string | null;
  selectedPostcode: string;
  selectedUprn: number | null;
  selectedPropertyType: string | null;
  selectedBuiltForm: string | null;
  isSubmitting: boolean;
  onSubmitRemoteAssessment: (values: RemoteAssessmentFormValues) => void;
  setSelectedScenario: (scenarioId: string | null) => void;
  selectedScenario: string | null;
}) {
  const NEW_SENTINEL = "__new__";

  const [showMeasures, setShowMeasures] = useState(false);

  const form = useForm<RemoteAssessmentFormValues>({
    resolver: zodResolver(RemoteAssessmentFormSchema),
    mode: "onChange",
    defaultValues: {
      scenario: "",
      goal: "",
      goalValue: "",
      budget: undefined,
      housingType: "Social",
      addressLineOne: "",
      postcode: "",
      uprn: 1,
      measures: measuresList,
    },
  });

  const { setValue, watch, handleSubmit, formState } = form;
  const values = watch();
  const [localSubmitting, setLocalSubmitting] = useState(false);

  const scenarioOptions: ScenarioOption[] = useMemo(
    () =>
      scenarios.map((s) => ({
        label: s.name || "",
        value: String(s.id) || "",
        housingType: s.housingType || "",
        goal: s.goal || "",
        goalValue: s.goalValue || "",
      })),
    [scenarios]
  );

  function handleSelect(opt: ScenarioOption) {
    setSelectedScenario(opt.value);

    if (opt.value === NEW_SENTINEL) {
      form.reset({
        ...form.getValues(),
        scenario: "",
        housingType: "",
        goal: "",
        goalValue: "",
        budget: undefined,
        measures: measuresList,
        addressLineOne: selectedAddress || "",
        postcode: selectedPostcode || "",
        uprn: selectedUprn || undefined,
        propertyType: selectedPropertyType || null,
        builtForm: selectedBuiltForm || null,
      });
    } else {
      form.reset({
        scenario: opt.label || "",
        housingType: opt.housingType || "",
        goal: opt.goal || "",
        goalValue: opt.goalValue || "",
        budget: undefined,
        measures: measuresList,
        addressLineOne: selectedAddress || "",
        postcode: selectedPostcode || "",
        uprn: selectedUprn || undefined,
        propertyType: selectedPropertyType || null,
        builtForm: selectedBuiltForm || null,
      });
    }
  }

  async function onSubmit(data: RemoteAssessmentFormValues) {
    setLocalSubmitting(true);
    // Keep the button in submitting state until redirect completes
    await onSubmitRemoteAssessment(data);
  }

  return (
    <Card
      className={`p-6 transition-all ${
        disabled
          ? "opacity-50 pointer-events-none cursor-not-allowed"
          : "opacity-100 cursor-default"
      }`}
    >
      <FormProvider {...form}>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <div>
            <label className="block text-gray-800 text-sm font-medium mb-2">
              Select Scenario
            </label>
            <SelectScenarioDropdown
              selectedValue={selectedScenario}
              onSelect={handleSelect}
              scenarios={scenarioOptions}
            />
          </div>

          {selectedScenario && (
            <>
              {/* Scenario Name + Housing Type */}
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="scenario"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Scenario Name</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={selectedScenario !== NEW_SENTINEL}
                          placeholder="Enter scenario name"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="housingType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Housing Type</FormLabel>
                      <FormControl>
                        {selectedScenario === NEW_SENTINEL ? (
                          <SelectDropdown
                            options={housingTypeOptions}
                            selectedOption={field.value}
                            onSelectOption={(opt) => field.onChange(opt.value)}
                          />
                        ) : (
                          <Input value={field.value} disabled />
                        )}
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {/* Goal + EPC */}
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="goal"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Goal</FormLabel>
                      <FormControl>
                        {selectedScenario === NEW_SENTINEL ? (
                          <SelectDropdown
                            options={[
                              {
                                label: "Increasing EPC",
                                value: "Increasing EPC",
                              },
                              {
                                label: "Energy Savings",
                                value: "Energy Savings",
                              },
                              {
                                label: "Reducing CO₂ emissions",
                                value: "Reducing CO2 emissions",
                              },
                            ]}
                            selectedOption={field.value}
                            onSelectOption={(opt) => field.onChange(opt.value)}
                          />
                        ) : (
                          <Input value={field.value} disabled />
                        )}
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {values.goal === "Increasing EPC" && (
                  <FormField
                    control={form.control}
                    name="goalValue"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Target EPC Rating</FormLabel>
                        <FormControl>
                          {selectedScenario === NEW_SENTINEL ? (
                            <SelectDropdown
                              options={[
                                { label: "C", value: "C" },
                                { label: "B", value: "B" },
                                { label: "A", value: "A" },
                              ]}
                              selectedOption={field.value || ""}
                              onSelectOption={(opt) =>
                                field.onChange(opt.value)
                              }
                            />
                          ) : (
                            <Input value={field.value || ""} disabled />
                          )}
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>

              {/* Measures Section */}
              <div className="border-t pt-4 mt-6">
                <button
                  type="button"
                  onClick={() => setShowMeasures(!showMeasures)}
                  className="flex items-center justify-between w-full text-sm font-medium text-gray-800"
                >
                  <span>Measures</span>
                  <span>{showMeasures ? "−" : "+"}</span>
                </button>
                {showMeasures && <MeasuresCheckboxes form={form} />}
              </div>
              <div className="flex justify-end pt-6">
                <Button
                  type="button"
                  disabled={isSubmitting || localSubmitting}
                  onClick={() =>
                    handleSubmit(onSubmit, (err) =>
                      console.log("Validation failed:", err)
                    )()
                  }
                  className="flex items-center gap-2 bg-brandblue text-white py-3 font-semibold hover:bg-hoverblue"
                >
                  {isSubmitting || localSubmitting ? (
                    <>
                      <svg
                        className="animate-spin h-5 w-5 text-white"
                        xmlns="http://www.w3.org/2000/svg"
                        fill="none"
                        viewBox="0 0 24 24"
                      >
                        <circle
                          className="opacity-25"
                          cx="12"
                          cy="12"
                          r="10"
                          stroke="currentColor"
                          strokeWidth="4"
                        />
                        <path
                          className="opacity-75"
                          fill="currentColor"
                          d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
                        />
                      </svg>
                      Submitting...
                    </>
                  ) : (
                    <>
                      <Play className="w-5 h-5" />
                      Run Assessment
                    </>
                  )}
                </Button>
              </div>
            </>
          )}
        </form>
      </FormProvider>
    </Card>
  );
}
