"use client";

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";
import { Button } from "@/app/shadcn_components/ui/button";
import { Input } from "@/app/shadcn_components/ui/input";
import { Label } from "@/app/shadcn_components/ui/label";
import { useState, useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import { PropertyMeta } from "@/app/db/schema/property";
import { cache } from "react";
import { useSession } from "next-auth/react";


interface BookSurveyModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  propertyId: bigint;
  portfolioId: string;
  propertyMeta: PropertyMeta;
  onSuccess?: () => void; // ✅ fix: properly declare optional callback
}


export default function BookSurveyModal({
  open,
  onOpenChange,
  propertyId,
  portfolioId,
  propertyMeta,
  onSuccess, // ✅ fix: remove “?:” here, we already declared it optional in interface
}: BookSurveyModalProps) {
  const { data: session, status } = useSession();

  const user = session?.user;


  // 🧠 Simple mutation to call your HubSpot API
  const bookSurveyMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch("/api/book-survey", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          pipelineId: "2400089278",
          dealStageId: "3660660975",
          propertyId: propertyId.toString(),
          portfolioId: portfolioId,
          userInfo: user,
          propertyMeta: propertyMeta,
        }),
      });

      if (!res.ok) throw new Error("Failed to create HubSpot deal");
      return res.json();
    },
    onSuccess: (data) => {
      console.log("✅ Deal created successfully:", data);
      console.log("HUBSPOT DEAL ID MADE", data.dealId);
      onOpenChange(false);
      if (onSuccess) onSuccess(); // 👈 trigger confetti toast
    },
    onError: (error) => {
      console.error("❌ Deal creation failed:", error);
    },
  });

  // 🚀 Submit
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    bookSurveyMutation.mutate();
  };

  return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Full On-Site Retrofit Assessment</DialogTitle>
          </DialogHeader>

          <div className="space-y-4 text-sm text-muted-foreground">
            <p>
              An in-person survey carried out by one of our retrofit specialists.
              This is recommended where a desktop review isn’t sufficient or where
              a clear, evidence-based plan is required.
            </p>

            <div>
              <p className="font-medium text-foreground mb-2">What’s included</p>
              <ul className="list-disc pl-5 space-y-1">
                <li>Detailed inspection of the property</li>
                <li>Verification of construction, insulation, heating and ventilation</li>
                <li>Assessment of damp, moisture and occupancy risks</li>
                <li>PAS 2035-compliant retrofit plan with clear recommendations</li>
              </ul>
            </div>

            <div>
              <p className="font-medium text-foreground mb-2">What happens next</p>
              <ul className="list-disc pl-5 space-y-1">
                <li>Arrange a suitable assessment date</li>
                <li>Confirm access details</li>
                <li>Take payment and complete the booking</li>
              </ul>
            </div>
          </div>

          <form onSubmit={handleSubmit}>
            <DialogFooter className="pt-4">
              <Button
                type="submit"
                className="w-full"
                disabled={bookSurveyMutation.isPending}
              >
                {bookSurveyMutation.isPending ? "Creating…" : "Confirm"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    );
}


// TODO: check if bug is happening and why.
// TODO: Ask khalim what we want to do, maybe a list of Hubspot DB record? if someone presses twice, currently just updates
// TODO: Make a sexy toast that the deal has been processed
// TODO: Show khalim a demo and other clean ups for good user experience