"use client";

import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { formatDateTime } from "./primitives";

const SURVEY_TYPES = [
  { value: "technical_building_survey", label: "Technical Building Survey" },
] as const;

type SurveyRequestRecord = {
  id: string;
  hubspotDealId: string;
  surveyType: string | null;
  status: string;
  requestedByEmail: string;
  requestedAt: string | null;
  fulfilledAt: string | null;
};

export function SurveyRequestSection({
  dealId,
  portfolioId,
  canEdit,
}: {
  dealId: string;
  portfolioId: string;
  canEdit: boolean;
}) {
  const queryClient = useQueryClient();
  const [selectedType, setSelectedType] = useState<string>(SURVEY_TYPES[0].value);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const { data, isLoading } = useQuery<{ requests: SurveyRequestRecord[] }>({
    queryKey: ["surveyRequests", portfolioId, dealId],
    queryFn: async () => {
      const res = await fetch(
        `/api/portfolio/${portfolioId}/survey-requests?dealId=${encodeURIComponent(dealId)}`,
      );
      if (!res.ok) throw new Error("Failed to fetch survey requests");
      return res.json();
    },
    staleTime: 30_000,
  });

  const pending = data?.requests?.find((r) => r.status === "pending") ?? null;
  const fulfilled = (data?.requests ?? []).filter((r) => r.status === "fulfilled");

  async function handleSubmit() {
    if (submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch(`/api/portfolio/${portfolioId}/survey-requests`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ hubspotDealId: dealId, surveyType: selectedType }),
      });
      if (!res.ok) {
        const json = await res.json().catch(() => ({}));
        setError(typeof json.error === "string" ? json.error : "Failed to submit request");
        return;
      }
      const json = (await res.json()) as { ok: boolean; hubspotSync?: string; hubspotError?: string };
      if (json.hubspotSync === "failed") {
        setError(json.hubspotError ? `Saved locally — HubSpot sync failed: ${json.hubspotError}` : "Saved locally — HubSpot sync failed");
      }
      queryClient.invalidateQueries({ queryKey: ["surveyRequests", portfolioId, dealId] });
    } finally {
      setSubmitting(false);
    }
  }

  function surveyTypeLabel(value: string | null) {
    if (!value) return value;
    return SURVEY_TYPES.find((t) => t.value === value)?.label ?? value;
  }

  if (isLoading) {
    return <p className="text-xs text-gray-400 py-2">Loading…</p>;
  }

  return (
    <div data-testid="survey-request-form" className="space-y-3">
      {error && (
        <p className="text-xs text-red-600 bg-red-50 px-3 py-2 rounded-lg">{error}</p>
      )}

      {!pending && fulfilled.length === 0 && (
        <p className="text-xs text-gray-400 py-1">No surveys requested</p>
      )}

      {pending && (
        <div
          data-testid="survey-request-pending-badge"
          className="rounded-xl border border-amber-200 bg-amber-50 p-3.5 space-y-1.5"
        >
          <span className="text-xs font-semibold text-amber-700 bg-amber-100 px-2 py-0.5 rounded-full border border-amber-200">
            Survey Requested
          </span>
          <p className="text-xs text-gray-700 font-medium">{surveyTypeLabel(pending.surveyType)}</p>
          <p className="text-[11px] text-gray-400">
            Requested by{" "}
            <span className="font-medium text-gray-600">{pending.requestedByEmail}</span>
            {pending.requestedAt && ` · ${formatDateTime(pending.requestedAt)}`}
          </p>
        </div>
      )}

      {canEdit && !pending && (
        <div className="space-y-2">
          <label className="flex flex-col gap-1">
            <span className="text-xs text-gray-500 font-medium">Survey type</span>
            <select
              data-testid="survey-request-type-select"
              value={selectedType}
              onChange={(e) => setSelectedType(e.target.value)}
              disabled={submitting}
              className="rounded-lg border border-gray-200 px-3 py-1.5 text-xs text-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-300 bg-white"
            >
              {SURVEY_TYPES.map((t) => (
                <option key={t.value} value={t.value}>{t.label}</option>
              ))}
            </select>
          </label>
          <div className="flex justify-end">
            <button
              data-testid="survey-request-submit"
              type="button"
              onClick={handleSubmit}
              disabled={submitting}
              className="text-xs font-medium px-3 py-1.5 rounded-lg bg-brandblue text-white hover:bg-brandmidblue disabled:opacity-50 transition-colors"
            >
              {submitting ? "Submitting…" : "Request Survey"}
            </button>
          </div>
        </div>
      )}

      {fulfilled.length > 0 && (
        <div className="space-y-1.5 pt-1">
          <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400">Past Requests</p>
          {fulfilled.map((r) => (
            <div key={r.id} className="rounded-lg border border-emerald-100 bg-emerald-50/50 px-3 py-2.5 space-y-1">
              <span className="text-[10px] font-semibold text-emerald-700">Fulfilled</span>
              <p className="text-xs text-gray-700 font-medium">{surveyTypeLabel(r.surveyType)}</p>
              <p className="text-[11px] text-gray-400">
                By <span className="font-medium text-gray-600">{r.requestedByEmail}</span>
                {r.requestedAt && ` · ${formatDateTime(r.requestedAt)}`}
              </p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
