"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { ReactSelect } from "@/components/ui/react-select";
import { DollarSign, Link as LinkIcon, Loader2 } from "lucide-react";
import { toast } from "sonner";
import {
  useUpdateCustomerExpansionMutation,
  useUpdateCustomerMutation,
  type CustomerBackend,
} from "@/api/rtk/customers-api";

const SIGNAL_TYPE_OPTIONS = [
  { value: "Cross-sell", label: "Cross-sell" },
  { value: "Upsell", label: "Upsell" },
  { value: "Renewal", label: "Renewal" },
  { value: "Expansion", label: "Expansion" },
];

const URGENCY_OPTIONS = [
  { value: "Low", label: "Low" },
  { value: "Medium", label: "Medium" },
  { value: "High", label: "High" },
  { value: "Critical", label: "Critical" },
];

function FieldLabel({ children }: { children: React.ReactNode }) {
  return (
    <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5 select-none">
      {children}
    </label>
  );
}

function SectionHeading({
  icon,
  children,
}: {
  icon: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <div className="flex items-center gap-2 mb-4">
      <div className="h-8 w-8 rounded-lg bg-[#6C63FF]/10 flex items-center justify-center text-[#6C63FF]">
        {icon}
      </div>
      <h3 className="text-[14px] font-black text-gray-900 uppercase tracking-wider font-['Lexend_Deca']">
        {children}
      </h3>
    </div>
  );
}

function tlvEqual(a: string | number | null | undefined, b: string): boolean {
  const na =
    a === null || a === undefined || a === ""
      ? NaN
      : typeof a === "number"
        ? a
        : parseFloat(String(a));
  const nb = b.trim() === "" ? NaN : parseFloat(b);
  if (Number.isNaN(na) && Number.isNaN(nb)) return true;
  if (Number.isNaN(na) || Number.isNaN(nb)) return false;
  return Math.abs(na - nb) < 1e-6;
}

export function CustomerExpansionEditor({
  customerId,
  customer,
  canEdit,
}: {
  customerId: string;
  customer: CustomerBackend | undefined;
  canEdit: boolean;
}) {
  const [updateExpansion, { isLoading: savingExpansion }] =
    useUpdateCustomerExpansionMutation();
  const [updateCustomer, { isLoading: savingTlv }] =
    useUpdateCustomerMutation();

  const [totalLifetimeValue, setTotalLifetimeValue] = React.useState("");
  const [signalType, setSignalType] = React.useState("");
  const [urgency, setUrgency] = React.useState("");
  const [clientLanguage, setClientLanguage] = React.useState("");
  const [briefingPackage, setBriefingPackage] = React.useState("");
  const [accountContext, setAccountContext] = React.useState("");
  const [signalSummary, setSignalSummary] = React.useState("");

  React.useEffect(() => {
    if (!customer) return;
    const tlv = customer.totalLifetimeValue;
    setTotalLifetimeValue(
      tlv !== null && tlv !== undefined && tlv !== "" ? String(tlv) : "",
    );
    setSignalType(customer.signalType ?? "");
    setUrgency(customer.urgency ?? "");
    setClientLanguage(customer.clientLanguage ?? "");
    setBriefingPackage(customer.briefingPackage ?? "");
    setAccountContext(customer.accountContext ?? "");
    setSignalSummary(customer.signalSummary ?? "");
  }, [customer]);

  const saving = savingExpansion || savingTlv;

  const handleSave = async () => {
    if (!customer || !canEdit) return;
    try {
      await updateExpansion({
        id: customerId,
        expansion: {
          signalType: signalType || undefined,
          urgency: urgency || undefined,
          clientLanguage: clientLanguage || undefined,
          briefingPackage: briefingPackage || undefined,
          accountContext: accountContext || undefined,
          signalSummary: signalSummary || undefined,
        },
      }).unwrap();

      if (!tlvEqual(customer.totalLifetimeValue, totalLifetimeValue)) {
        const trimmed = totalLifetimeValue.trim();
        await updateCustomer({
          id: customerId,
          updates: {
            totalLifetimeValue: trimmed === "" ? null : parseFloat(trimmed),
          },
        }).unwrap();
      }

      toast.success("Expansion & value saved");
    } catch (e: unknown) {
      console.error(e);
      toast.error(e instanceof Error ? e.message : "Failed to save expansion");
    }
  };

  if (!customer) {
    return (
      <div className="flex items-center justify-center py-16 text-gray-500 text-sm">
        Loading customer…
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <section>
        <SectionHeading icon={<DollarSign size={14} />}>
          Deal value (total lifetime value)
        </SectionHeading>
        <div className="grid grid-cols-1 sm:max-w-md gap-4">
          <div>
            <FieldLabel>Value (USD)</FieldLabel>
            <Input
              type="number"
              step="0.01"
              className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
              value={totalLifetimeValue}
              onChange={(e) => setTotalLifetimeValue(e.target.value)}
              disabled={!canEdit}
              placeholder="0.00"
            />
          </div>
        </div>
      </section>

      <section>
        <SectionHeading icon={<LinkIcon size={14} />}>
          Expansion signals (account summary)
        </SectionHeading>
        <p className="text-[12px] text-gray-500 mb-4 max-w-2xl">
          High-level upsell / renewal context stored on the customer record.
          Detailed signal history stays in the list below.
        </p>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <FieldLabel>Signal type</FieldLabel>
            <ReactSelect
              value={signalType}
              onValueChange={setSignalType}
              options={SIGNAL_TYPE_OPTIONS}
              placeholder="Select type"
              allowEmpty
              disabled={!canEdit}
              triggerClassName="h-10 min-h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
              contentClassName="rounded-xl"
            />
          </div>
          <div>
            <FieldLabel>Urgency</FieldLabel>
            <ReactSelect
              value={urgency}
              onValueChange={setUrgency}
              options={URGENCY_OPTIONS}
              placeholder="Select urgency"
              allowEmpty
              disabled={!canEdit}
              triggerClassName="h-10 min-h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
              contentClassName="rounded-xl"
            />
          </div>
          <div className="sm:col-span-2">
            <FieldLabel>Exact client language</FieldLabel>
            <Textarea
              className="min-h-[60px] text-[14px] bg-gray-50 border-gray-200 rounded-xl resize-y"
              value={clientLanguage}
              onChange={(e) => setClientLanguage(e.target.value)}
              disabled={!canEdit}
              placeholder="What specifically did the client say?"
            />
          </div>
          <div>
            <FieldLabel>AE briefing package</FieldLabel>
            <Input
              className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
              value={briefingPackage}
              onChange={(e) => setBriefingPackage(e.target.value)}
              disabled={!canEdit}
              placeholder="Link or doc reference"
            />
          </div>
          <div>
            <FieldLabel>Account context</FieldLabel>
            <Input
              className="h-10 text-[14px] bg-gray-50 border-gray-200 rounded-xl"
              value={accountContext}
              onChange={(e) => setAccountContext(e.target.value)}
              disabled={!canEdit}
              placeholder="Key account details"
            />
          </div>
          <div className="sm:col-span-2">
            <FieldLabel>Signal summary</FieldLabel>
            <Textarea
              className="min-h-[60px] text-[14px] bg-gray-50 border-gray-200 rounded-xl resize-y"
              value={signalSummary}
              onChange={(e) => setSignalSummary(e.target.value)}
              disabled={!canEdit}
              placeholder="Summarize the opportunity"
            />
          </div>
        </div>
      </section>

      {canEdit ? (
        <div className="flex justify-end pt-2 border-t border-gray-100">
          <Button
            type="button"
            className="rounded-xl bg-[#6C63FF] hover:bg-[#5a52e6] gap-2"
            onClick={() => void handleSave()}
            loading={saving}
          >
            Save expansion
          </Button>
        </div>
      ) : (
        <p className="text-[12px] text-gray-500">
          You do not have permission to edit customer expansion fields.
        </p>
      )}
    </div>
  );
}
