"use client";

import * as React from "react";
import { Plus, Pencil, Trash2, Settings2, Save, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ReactSelect } from "@/components/ui/react-select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import {
  useGetBantOptionsQuery,
  useCreateBantScoreMutation,
  useUpdateBantScoreMutation,
  useDeleteBantScoreMutation,
  useCreateBantBudgetMutation,
  useUpdateBantBudgetMutation,
  useDeleteBantBudgetMutation,
  useCreateBantAuthorityMutation,
  useUpdateBantAuthorityMutation,
  useDeleteBantAuthorityMutation,
  useCreateBantNeedMutation,
  useUpdateBantNeedMutation,
  useDeleteBantNeedMutation,
  useCreateBantTimelineMutation,
  useUpdateBantTimelineMutation,
  useDeleteBantTimelineMutation,
} from "@/api/rtk/bant-options-api";

interface BantSelectManagedProps {
  label: string;
  value: string;
  options: any[];
  onChange: (v: string) => void;
  desc: string;
  ui: any;
  onUiChange: (u: any) => void;
  onCreate: (n: string) => Promise<void>;
  onUpdate: (id: string, n: string) => Promise<void>;
  onDelete: (id: string) => Promise<void>;
  className?: string;
}

function BantSelectManaged({
  label,
  value,
  options,
  onChange,
  desc,
  ui,
  onUiChange,
  onCreate,
  onUpdate,
  onDelete,
  className,
}: BantSelectManagedProps) {
  const selectOptions = React.useMemo(
    () => [
      // ReactSelect needs a non-empty sentinel; map back to "" so PATCH clears the FK.
      { value: "__none", label: "Not Specified" },
      ...options.map((o) => ({ value: o.id, label: o.name })),
    ],
    [options],
  );

  return (
    <div className={cn("p-6 rounded-2xl bg-white/30 backdrop-blur-sm border border-gray-100 hover:border-[#6C63FF]/30 transition-all group", className)}>
      <div className="flex items-center justify-between mb-4">
        <span className="text-[10px] font-bold text-gray-400 uppercase tracking-widest font-['Lexend_Deca']">{label}</span>
        <div className="flex items-center gap-1 opacity-20 group-hover:opacity-100 transition-opacity">
          <Popover open={ui.addOpen} onOpenChange={(o) => onUiChange({ addOpen: o })}>
            <PopoverTrigger asChild>
              <Button variant="ghostIconTight">
                <Plus size={14} />
              </Button>
            </PopoverTrigger>
            <PopoverContent align="end" className="w-64 p-3 rounded-xl shadow-2xl border-gray-100">
              <p className="text-[11px] font-bold text-gray-500 uppercase mb-3">Add New {label}</p>
              <Input
                value={ui.newName}
                onChange={(e) => onUiChange({ newName: e.target.value })}
                placeholder="Option name..."
                className="h-9 text-sm mb-3 rounded-lg"
                onKeyDown={(e) => e.key === "Enter" && ui.newName.trim() && (onCreate(ui.newName.trim()), onUiChange({ addOpen: false, newName: "" }))}
              />
              <Button
                variant="default"
                size="fullSm"
                disabled={!ui.newName.trim()}
                onClick={() => {
                  onCreate(ui.newName.trim());
                  onUiChange({ addOpen: false, newName: "" });
                }}
              >
                Add Option
              </Button>
            </PopoverContent>
          </Popover>

          <Popover open={ui.manageOpen} onOpenChange={(o) => onUiChange({ manageOpen: o, editingId: null })}>
            <PopoverTrigger asChild>
              <Button variant="ghostIconTightMuted">
                <Settings2 size={14} />
              </Button>
            </PopoverTrigger>
            <PopoverContent align="end" className="w-72 p-2 rounded-xl shadow-2xl border-gray-100">
              <p className="text-[11px] font-bold text-gray-500 uppercase px-2 py-2 mb-1 border-b border-gray-100/50">Manage {label}s</p>
              <div className="max-h-60 overflow-y-auto space-y-1 p-1">
                {options.length === 0 && <p className="text-[12px] text-gray-400 text-center py-4">No options added yet.</p>}
                {options.map((o) => (
                  <div key={o.id} className="flex items-center gap-2 p-1.5 rounded-lg hover:bg-gray-50 group/item">
                    {ui.editingId === o.id ? (
                      <>
                        <Input
                          value={ui.editingName}
                          onChange={(e) => onUiChange({ editingName: e.target.value })}
                          className="h-8 text-[13px] flex-1"
                          autoFocus
                        />
                        <Button
                          size="sm"
                          onClick={() => {
                            onUpdate(o.id, ui.editingName);
                            onUiChange({ editingId: null });
                          }}
                        >
                          Save
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => onUiChange({ editingId: null })}>
                          Cancel
                        </Button>
                      </>
                    ) : (
                      <>
                        <span className="text-[13px] font-medium flex-1 px-2">{o.name}</span>
                        <Button variant="ghostIconTightMutedReveal" onClick={() => onUiChange({ editingId: o.id, editingName: o.name })}>
                          <Pencil size={12} />
                        </Button>
                        <Button variant="ghostIconTightDangerReveal" onClick={() => onDelete(o.id)}>
                          <Trash2 size={12} />
                        </Button>
                      </>
                    )}
                  </div>
                ))}
              </div>
            </PopoverContent>
          </Popover>
        </div>
      </div>
      <ReactSelect
        value={value || "__none"}
        onValueChange={(v) => onChange(v === "__none" ? "" : v)}
        options={selectOptions}
        placeholder={`Select ${label}...`}
        triggerClassName="h-12 min-h-12 w-full bg-gray-100/30 border-gray-100 rounded-xl transition-all focus:border-[#6C63FF]/40 focus:ring-0"
        contentClassName="rounded-xl border-gray-100 shadow-2xl backdrop-blur-xl bg-white/90"
      />
      <p className="mt-4 text-[11px] text-gray-400 font-medium leading-relaxed italic opacity-80 group-hover:opacity-100 transition-opacity">{desc}</p>
    </div>
  );
}

const BANT_GRID_COLUMNS_CLASS = {
  1: "grid-cols-1",
  2: "grid-cols-1 sm:grid-cols-2",
  3: "grid-cols-1 md:grid-cols-2 lg:grid-cols-3",
} as const;

interface BantQualificationGridProps {
  value: {
    bantScoreId?: string;
    bantBudgetId?: string;
    bantAuthorityId?: string;
    bantNeedId?: string;
    bantTimelineId?: string;
  };
  onChange: (field: string, value: string) => void;
  /** Column count should match the layout share (e.g. 1 in the lead-detail sidebar). */
  columns?: keyof typeof BANT_GRID_COLUMNS_CLASS;
}

/**
 * Controlled BANT pickers with inline catalog CRUD. Unset dimensions use `""`; the select
 * uses `__none` internally. Deleting the selected option clears that dimension on `value`.
 */
export function BantQualificationGrid({ value, onChange, columns = 3 }: BantQualificationGridProps) {
  const { data: bantOptions } = useGetBantOptionsQuery();
  const scores = bantOptions?.scores || [];
  const budgets = bantOptions?.budgets || [];
  const authorities = bantOptions?.authorities || [];
  const needs = bantOptions?.needs || [];
  const timelines = bantOptions?.timelines || [];

  const [createBantScore] = useCreateBantScoreMutation();
  const [updateBantScore] = useUpdateBantScoreMutation();
  const [deleteBantScore] = useDeleteBantScoreMutation();

  const [createBantBudget] = useCreateBantBudgetMutation();
  const [updateBantBudget] = useUpdateBantBudgetMutation();
  const [deleteBantBudget] = useDeleteBantBudgetMutation();

  const [createBantAuthority] = useCreateBantAuthorityMutation();
  const [updateBantAuthority] = useUpdateBantAuthorityMutation();
  const [deleteBantAuthority] = useDeleteBantAuthorityMutation();

  const [createBantNeed] = useCreateBantNeedMutation();
  const [updateBantNeed] = useUpdateBantNeedMutation();
  const [deleteBantNeed] = useDeleteBantNeedMutation();

  const [createBantTimeline] = useCreateBantTimelineMutation();
  const [updateBantTimeline] = useUpdateBantTimelineMutation();
  const [deleteBantTimeline] = useDeleteBantTimelineMutation();

  const [bantUi, setBantUi] = React.useState<Record<string, { addOpen: boolean; newName: string; manageOpen: boolean; editingId: string | null; editingName: string }>>({
    bantScore: { addOpen: false, newName: "", manageOpen: false, editingId: null, editingName: "" },
    bantBudget: { addOpen: false, newName: "", manageOpen: false, editingId: null, editingName: "" },
    bantAuthority: { addOpen: false, newName: "", manageOpen: false, editingId: null, editingName: "" },
    bantNeed: { addOpen: false, newName: "", manageOpen: false, editingId: null, editingName: "" },
    bantTimeline: { addOpen: false, newName: "", manageOpen: false, editingId: null, editingName: "" },
  });

  const setBantField = (field: string, updates: any) => {
    setBantUi((prev) => ({
      ...prev,
      [field]: { ...prev[field], ...updates },
    }));
  };

  return (
    <div className={cn("grid gap-6", BANT_GRID_COLUMNS_CLASS[columns])}>
      <BantSelectManaged
        label="BANT Score"
        value={value.bantScoreId || ""}
        options={scores}
        onChange={(v) => onChange("bantScoreId", v)}
        desc="Overall lead quality assessment."
        ui={bantUi.bantScore}
        onUiChange={(u) => setBantField("bantScore", u)}
        onCreate={async (n) => {
          const r = await createBantScore({ name: n }).unwrap();
          onChange("bantScoreId", r.id);
        }}
        onUpdate={async (id, n) => {
          await updateBantScore({ id, name: n }).unwrap();
        }}
        onDelete={async (id) => {
          await deleteBantScore(id).unwrap();
          if (value.bantScoreId === id) onChange("bantScoreId", "");
        }}
      />

      <BantSelectManaged
        label="BANT Budget"
        value={value.bantBudgetId || ""}
        options={budgets}
        onChange={(v) => onChange("bantBudgetId", v)}
        desc="Categorized budget range for this lead."
        ui={bantUi.bantBudget}
        onUiChange={(u) => setBantField("bantBudget", u)}
        onCreate={async (n) => {
          const r = await createBantBudget({ name: n }).unwrap();
          onChange("bantBudgetId", r.id);
        }}
        onUpdate={async (id, n) => {
          await updateBantBudget({ id, name: n }).unwrap();
        }}
        onDelete={async (id) => {
          await deleteBantBudget(id).unwrap();
          if (value.bantBudgetId === id) onChange("bantBudgetId", "");
        }}
      />

      <BantSelectManaged
        label="BANT Authority"
        value={value.bantAuthorityId || ""}
        options={authorities}
        onChange={(v) => onChange("bantAuthorityId", v)}
        desc="Decision-making power assessment."
        ui={bantUi.bantAuthority}
        onUiChange={(u) => setBantField("bantAuthority", u)}
        onCreate={async (n) => {
          const r = await createBantAuthority({ name: n }).unwrap();
          onChange("bantAuthorityId", r.id);
        }}
        onUpdate={async (id, n) => {
          await updateBantAuthority({ id, name: n }).unwrap();
        }}
        onDelete={async (id) => {
          await deleteBantAuthority(id).unwrap();
          if (value.bantAuthorityId === id) onChange("bantAuthorityId", "");
        }}
      />

      <BantSelectManaged
        label="BANT Need"
        value={value.bantNeedId || ""}
        options={needs}
        onChange={(v) => onChange("bantNeedId", v)}
        desc="Pain point or business requirement level."
        ui={bantUi.bantNeed}
        onUiChange={(u) => setBantField("bantNeed", u)}
        onCreate={async (n) => {
          const r = await createBantNeed({ name: n }).unwrap();
          onChange("bantNeedId", r.id);
        }}
        onUpdate={async (id, n) => {
          await updateBantNeed({ id, name: n }).unwrap();
        }}
        onDelete={async (id) => {
          await deleteBantNeed(id).unwrap();
          if (value.bantNeedId === id) onChange("bantNeedId", "");
        }}
      />

      <BantSelectManaged
        label="BANT Timeline"
        value={value.bantTimelineId || ""}
        options={timelines}
        onChange={(v) => onChange("bantTimelineId", v)}
        desc="Estimated decision timeframe window."
        ui={bantUi.bantTimeline}
        onUiChange={(u) => setBantField("bantTimeline", u)}
        onCreate={async (n) => {
          const r = await createBantTimeline({ name: n }).unwrap();
          onChange("bantTimelineId", r.id);
        }}
        onUpdate={async (id, n) => {
          await updateBantTimeline({ id, name: n }).unwrap();
        }}
        onDelete={async (id) => {
          await deleteBantTimeline(id).unwrap();
          if (value.bantTimelineId === id) onChange("bantTimelineId", "");
        }}
      />
    </div>
  );
}
