"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import AddressSearch from "./AddressSearch";
import ScenarioSetup from "./ScenarioSetup";
import { ScenarioSelect, measuresList } from "@/app/db/schema/recommendations";
import useCreateRemoteAssessment from "./useCreateRemoteAssessment";
import { RemoteAssessmentFormValues } from "@/app/portfolio/[slug]/components/FormSchema";
import BackToPortfolioButton from "@/app/components/building-passport/BackToPortfolioButton";
import { MapPin, ClipboardCheck, Zap } from "lucide-react";

export default function RemoteAssessmentClient({
  portfolioId,
  scenarios,
}: {
  portfolioId: string;
  scenarios: ScenarioSelect[];
}) {
  const router = useRouter();
  const [selectedAddress, setSelectedAddress] = useState<{
    address: string;
    uprn: string;
    propertyType?: string;
    builtForm?: string;
  } | null>(null);
  const [selectedPostcode, setSelectedPostcode] = useState<string>("");
  const [selectedScenario, setSelectedScenario] = useState<string | null>(null);

  const { handleSubmit: submitAssessment, isUploading } =
    useCreateRemoteAssessment({
      portfolioId,
      uprn: selectedAddress?.uprn ? parseInt(selectedAddress.uprn) : null,
      addressLineOne: selectedAddress?.address || "",
      postcode: selectedPostcode,
      valuation: null,
      propertyType: selectedAddress?.propertyType || null,
      builtForm: selectedAddress?.builtForm || null,
      measures: measuresList,
      scenarioId: selectedScenario,
    });

  async function onSubmitRemoteAssessment(values: RemoteAssessmentFormValues) {
    await submitAssessment(values);
    router.push(`/portfolio/${portfolioId}/plan-loading`);
  }

  return (
    <div className="min-h-screen flex flex-col bg-gradient-to-b from-gray-50 to-white">
      {/* --- HERO / EXPLANATION SECTION --- */}
      <div className="relative bg-gradient-to-r from-brandblue to-midblue text-white overflow-hidden">
        <div
          className="absolute inset-0 bg-cover bg-center opacity-20"
          style={{
            backgroundImage: "url('/images/energy-analysis-placeholder.webp')",
          }}
        />

        <div className="relative z-10 max-w-7xl mx-auto px-8 py-8 md:py-10 flex flex-col gap-6">
          {/* Title & back button pinned to top */}
          <div className="flex items-center gap-4 mb-4">
            <BackToPortfolioButton portfolioId={portfolioId} />
            <h1 className="text-3xl md:text-4xl font-bold">
              Remote Assessment
            </h1>
          </div>

          {/* Hero text split to use horizontal space better */}
          <div className="flex flex-col md:flex-row justify-between gap-10">
            <p className="text-lg md:text-xl text-white/90 leading-relaxed max-w-2xl">
              Ara analyses your property data, models retrofit options, and
              estimates potential funding — all without an on-site survey.
            </p>
            <p className="text-sm text-white/70 max-w-md md:text-right">
              Start by selecting your property, then choose retrofit goals and
              configurations. Our model will generate your baseline and plan.
              This isn`&apos;`t a replacement for an on-site survey but a
              powerful first step.
            </p>
          </div>

          {/* Step indicators */}
          <div className="flex gap-6 mt-6 text-sm text-white/80 justify-start md:justify-center">
            <div className="flex items-center gap-2">
              <MapPin className="w-5 h-5" /> Find Address
            </div>
            <div className="w-8 h-[1px] bg-white/50" />
            <div className="flex items-center gap-2">
              <ClipboardCheck className="w-5 h-5" /> Configure Scenario
            </div>
            <div className="w-8 h-[1px] bg-white/50" />
            <div className="flex items-center gap-2">
              <Zap className="w-5 h-5" /> Generate Plan
            </div>
          </div>
        </div>

        {/* Optional subtle fade transition into workspace */}
        <div className="absolute bottom-0 left-0 w-full h-2 bg-gradient-to-r from-brandblue/30 to-midblue/30 blur-sm"></div>
      </div>

      {/* --- TWO-COLUMN WORKSPACE --- */}
      <div className="flex-1 max-w-7xl mx-auto w-full px-8 py-8">
        <div className="grid md:grid-cols-2 gap-6 items-stretch auto-rows-fr">
          {/* LEFT: Address Search */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="flex flex-col bg-white border border-gray-100 shadow-lg rounded-2xl p-8"
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-semibold text-brandbrown">
                Step 1: Find your property
              </h2>
              <p className="text-xs text-gray-500">Address lookup</p>
            </div>

            <AddressSearch
              onAddressSelect={(addr) => setSelectedAddress(addr)}
              onPostcodeSelect={setSelectedPostcode}
              postcode={selectedPostcode}
            />
          </motion.div>

          {/* RIGHT: Scenario Setup */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1, duration: 0.6 }}
            className={`flex flex-col bg-white border border-gray-100 shadow-lg rounded-2xl p-8 transition-opacity duration-300 ${
              selectedAddress ? "opacity-100" : "opacity-40 pointer-events-none"
            }`}
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-semibold text-brandbrown">
                Step 2: Configure scenario
              </h2>
              <p className="text-xs text-gray-500">Your model setup</p>
            </div>

            <div className="flex-grow flex flex-col">
              <ScenarioSetup
                portfolioId={portfolioId}
                scenarios={scenarios}
                disabled={!selectedAddress}
                selectedAddress={selectedAddress?.address ?? ""}
                selectedPostcode={selectedPostcode}
                selectedUprn={Number(selectedAddress?.uprn) ?? null}
                selectedPropertyType={selectedAddress?.propertyType ?? null}
                selectedBuiltForm={selectedAddress?.builtForm ?? null}
                isSubmitting={isUploading}
                onSubmitRemoteAssessment={onSubmitRemoteAssessment}
                setSelectedScenario={setSelectedScenario}
                selectedScenario={selectedScenario}
              />
            </div>
          </motion.div>
        </div>
      </div>

      {/* --- FOOTER NOTE --- */}
      <div className="pb-8 text-center text-xs text-gray-500">
        All assessments use verified EPC, OS AddressBase, and open data sources.
      </div>
    </div>
  );
}
