"use client";

import { useMemo, useState } from "react";
import { apiPatch } from "@/lib/api";
import type { CRMStage } from "@/types";

const STAGE_OPTIONS: Array<{ value: CRMStage; label: string }> = [
  { value: "LEAD", label: "Lead" },
  { value: "CONTACTED", label: "Contacted" },
  { value: "WARM", label: "Warm" },
  { value: "HOT", label: "Hot" },
  { value: "ACTIVE_PARTNER", label: "Active Partner / Customer" },
  { value: "PREMIUM_PARTNER", label: "Premium Partner / Customer" },
  { value: "INACTIVE", label: "Inactive" },
  { value: "LOST", label: "Lost" },
];

function formatDateInput(value?: string | null) {
  if (!value) return "";
  return new Date(value).toISOString().slice(0, 10);
}

function futureDate(days: number) {
  const next = new Date();
  next.setDate(next.getDate() + days);
  return next.toISOString().slice(0, 10);
}

export function CRMStageControls({
  endpoint,
  currentStage,
  lastContactedAt,
  nextFollowUpAt,
  onUpdated,
}: {
  endpoint: string;
  currentStage?: CRMStage | string | null;
  lastContactedAt?: string | null;
  nextFollowUpAt?: string | null;
  onUpdated: () => Promise<void> | void;
}) {
  const [stage, setStage] = useState<string>(currentStage ?? "LEAD");
  const [lastContact, setLastContact] = useState<string>(formatDateInput(lastContactedAt));
  const [followUp, setFollowUp] = useState<string>(formatDateInput(nextFollowUpAt));
  const [working, setWorking] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const quickStageButtons = useMemo(
    () => STAGE_OPTIONS.filter((option) => ["CONTACTED", "WARM", "HOT", "ACTIVE_PARTNER", "PREMIUM_PARTNER"].includes(option.value)),
    []
  );

  async function apply(payload: { crmStage?: string; lastContactedAt?: string | null; nextFollowUpAt?: string | null }) {
    try {
      setWorking(true);
      setError(null);
      await apiPatch(endpoint, payload);
      if (payload.crmStage !== undefined) setStage(payload.crmStage);
      if (payload.lastContactedAt !== undefined) setLastContact(payload.lastContactedAt ?? "");
      if (payload.nextFollowUpAt !== undefined) setFollowUp(payload.nextFollowUpAt ?? "");
      await onUpdated();
    } catch (e: any) {
      setError(e?.message ?? "Unable to update CRM lifecycle");
    } finally {
      setWorking(false);
    }
  }

  return (
    <section className="rounded-2xl border bg-white p-6 shadow-sm">
      <div className="mb-4">
        <h2 className="text-base font-semibold">Lifecycle controls</h2>
        <p className="mt-1 text-sm text-gray-500">Move this record through the CRM quickly and keep follow-up discipline visible.</p>
      </div>

      {error ? (
        <div className="mb-4 rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">{error}</div>
      ) : null}

      <div className="grid gap-4 lg:grid-cols-3">
        <label className="space-y-1">
          <span className="text-sm font-medium text-gray-700">CRM stage</span>
          <select
            value={stage}
            onChange={(e) => setStage(e.target.value)}
            className="w-full rounded-xl border bg-white px-3 py-2 text-sm"
            disabled={working}
          >
            {STAGE_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <button
            type="button"
            onClick={() => apply({ crmStage: stage })}
            disabled={working}
            className="rounded-xl border bg-white px-4 py-2 text-sm font-medium hover:bg-gray-50 disabled:opacity-60"
          >
            {working ? "Saving..." : "Save stage"}
          </button>
        </label>

        <label className="space-y-1">
          <span className="text-sm font-medium text-gray-700">Last contacted</span>
          <input
            type="date"
            value={lastContact}
            onChange={(e) => setLastContact(e.target.value)}
            className="w-full rounded-xl border bg-white px-3 py-2 text-sm"
            disabled={working}
          />
          <div className="flex flex-wrap gap-2">
            <button
              type="button"
              onClick={() => apply({ lastContactedAt: new Date().toISOString() })}
              disabled={working}
              className="rounded-xl border bg-white px-3 py-2 text-xs font-medium hover:bg-gray-50 disabled:opacity-60"
            >
              Log contact today
            </button>
            <button
              type="button"
              onClick={() => apply({ lastContactedAt: lastContact || null })}
              disabled={working}
              className="rounded-xl border bg-white px-3 py-2 text-xs font-medium hover:bg-gray-50 disabled:opacity-60"
            >
              Save contact date
            </button>
          </div>
        </label>

        <label className="space-y-1">
          <span className="text-sm font-medium text-gray-700">Next follow-up</span>
          <input
            type="date"
            value={followUp}
            onChange={(e) => setFollowUp(e.target.value)}
            className="w-full rounded-xl border bg-white px-3 py-2 text-sm"
            disabled={working}
          />
          <div className="flex flex-wrap gap-2">
            <button
              type="button"
              onClick={() => apply({ nextFollowUpAt: futureDate(3) })}
              disabled={working}
              className="rounded-xl border bg-white px-3 py-2 text-xs font-medium hover:bg-gray-50 disabled:opacity-60"
            >
              Follow up in 3 days
            </button>
            <button
              type="button"
              onClick={() => apply({ nextFollowUpAt: futureDate(7) })}
              disabled={working}
              className="rounded-xl border bg-white px-3 py-2 text-xs font-medium hover:bg-gray-50 disabled:opacity-60"
            >
              Follow up in 7 days
            </button>
            <button
              type="button"
              onClick={() => apply({ nextFollowUpAt: followUp || null })}
              disabled={working}
              className="rounded-xl border bg-white px-3 py-2 text-xs font-medium hover:bg-gray-50 disabled:opacity-60"
            >
              Save follow-up
            </button>
          </div>
        </label>
      </div>

      <div className="mt-5 border-t pt-5">
        <div className="mb-3 text-sm font-medium text-gray-700">Quick stage actions</div>
        <div className="flex flex-wrap gap-2">
          {quickStageButtons.map((option) => (
            <button
              key={option.value}
              type="button"
              onClick={() => apply({ crmStage: option.value })}
              disabled={working}
              className="rounded-xl border bg-white px-3 py-2 text-xs font-medium hover:bg-gray-50 disabled:opacity-60"
            >
              Mark {option.label}
            </button>
          ))}
          <button
            type="button"
            onClick={() => apply({ crmStage: "LOST" })}
            disabled={working}
            className="rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-xs font-medium text-red-700 hover:bg-red-100 disabled:opacity-60"
          >
            Mark Lost
          </button>
          <button
            type="button"
            onClick={() => apply({ crmStage: "INACTIVE" })}
            disabled={working}
            className="rounded-xl border bg-white px-3 py-2 text-xs font-medium hover:bg-gray-50 disabled:opacity-60"
          >
            Mark Inactive
          </button>
        </div>
      </div>
    </section>
  );
}
