"use client";

import * as React from "react";
import { UserPlus, Users } from "lucide-react";

import { ReactSelect } from "@/components/ui/react-select";
import { Button } from "@/components/ui/button";
import { ContributorUserPicker } from "@/components/deals/contributor-user-picker";
import { useGetLeadStatusesQuery } from "@/api/rtk/lead-statuses-api";
import { useGetBrandsQuery } from "@/api/rtk/brands-api";
import { useGetLeadChannelsQuery } from "@/api/rtk/lead-channels-api";
import { useGetTimelineIntentsQuery } from "@/api/rtk/deal-meta-api";
import { formatTeamLabelForUi } from "@/lib/deal-display";
import { cn } from "@/lib/utils";
import type {
  BulkAssignMode,
  BulkEditLeadsInput,
} from "@/features/leads/types";

const UNCHANGED = "__unchanged__";
const CLEAR = "__clear__";
const TEAM_NONE = "__none__";

export type BulkEditFieldsTeam = {
  id: string;
  name: string;
};

export type BulkEditFieldsValue = {
  leadStatusTouched: boolean;
  leadStatus: string;
  brandTouched: boolean;
  brand: string;
  leadChannelIdTouched: boolean;
  leadChannelId: string | null;
  timelineIntentTouched: boolean;
  timelineIntentId: string;
  teamTouched: boolean;
  team: string | null;
};

export const emptyBulkEditFieldsValue: BulkEditFieldsValue = {
  leadStatusTouched: false,
  leadStatus: "",
  brandTouched: false,
  brand: "",
  leadChannelIdTouched: false,
  leadChannelId: null,
  timelineIntentTouched: false,
  timelineIntentId: "",
  teamTouched: false,
  team: null,
};

export function buildBulkEditPayload(
  ids: string[],
  value: BulkEditFieldsValue,
): BulkEditLeadsInput {
  const payload: BulkEditLeadsInput = { ids };

  if (value.leadStatusTouched) {
    payload.leadStatus = value.leadStatus;
  }
  if (value.brandTouched) {
    payload.brand = value.brand;
  }
  if (value.leadChannelIdTouched) {
    payload.leadChannelId = value.leadChannelId ?? null;
  }
  if (value.timelineIntentTouched) {
    payload.timelineIntentId = value.timelineIntentId;
  }
  if (value.teamTouched) {
    payload.team = value.team ?? null;
  }

  return payload;
}

export function hasBulkEditChanges(value: BulkEditFieldsValue): boolean {
  return (
    value.leadStatusTouched ||
    value.brandTouched ||
    value.leadChannelIdTouched ||
    value.timelineIntentTouched ||
    value.teamTouched
  );
}

function teamSlugFor(team: BulkEditFieldsTeam): string {
  return team.name.toLowerCase().replace(/\s+/g, "-");
}

function UnchangedResetLink({ onReset }: { onReset: () => void }) {
  return (
    <Button
      type="button"
      variant="ghost"
      size="sm"
      className="h-7 text-[11px] px-0"
      onClick={onReset}
    >
      Leave unchanged
    </Button>
  );
}

export type BulkEditFieldsProps = {
  value: BulkEditFieldsValue;
  onChange: (next: BulkEditFieldsValue) => void;
  teams?: BulkEditFieldsTeam[];
  labelById?: Record<string, string | undefined>;
  skipQueries?: boolean;
  className?: string;
};

export function BulkEditFields({
  value,
  onChange,
  teams = [],
  labelById,
  skipQueries = false,
  className,
}: BulkEditFieldsProps) {
  const { data: leadStatuses = [] } = useGetLeadStatusesQuery(undefined, {
    skip: skipQueries,
  });
  const { data: leadChannels = [] } = useGetLeadChannelsQuery(undefined, {
    skip: skipQueries,
  });
  const { data: brands = [] } = useGetBrandsQuery(undefined, {
    skip: skipQueries,
  });
  const { data: timelineIntents = [] } = useGetTimelineIntentsQuery(undefined, {
    skip: skipQueries,
  });

  const leadStatusSelectValue = value.leadStatusTouched
    ? value.leadStatus === ""
      ? CLEAR
      : value.leadStatus
    : UNCHANGED;

  const brandSelectValue = value.brandTouched
    ? value.brand === ""
      ? CLEAR
      : value.brand
    : UNCHANGED;

  const teamSelectValue = value.teamTouched
    ? value.team === null
      ? TEAM_NONE
      : (value.team ?? TEAM_NONE)
    : UNCHANGED;

  const channelSelectValue = value.leadChannelIdTouched
    ? value.leadChannelId === null
      ? CLEAR
      : (value.leadChannelId ?? CLEAR)
    : UNCHANGED;

  const timelineIntentSelectValue = value.timelineIntentTouched
    ? value.timelineIntentId === ""
      ? CLEAR
      : value.timelineIntentId
    : UNCHANGED;

  const leadStatusOptions = React.useMemo(
    () => [
      { value: UNCHANGED, label: "Leave unchanged" },
      { value: CLEAR, label: "Clear lead status" },
      ...leadStatuses.map((s) => ({ value: s.name, label: s.name })),
    ],
    [leadStatuses],
  );

  const brandOptions = React.useMemo(
    () => [
      { value: UNCHANGED, label: "Leave unchanged" },
      { value: CLEAR, label: "Clear brand" },
      ...brands.map((b) => ({ value: b.name, label: b.name })),
    ],
    [brands],
  );

  const channelOptions = React.useMemo(
    () => [
      { value: UNCHANGED, label: "Leave unchanged" },
      { value: CLEAR, label: "Clear channel" },
      ...leadChannels.map((c) => ({ value: c.id, label: c.name })),
    ],
    [leadChannels],
  );

  const timelineIntentOptions = React.useMemo(
    () => [
      { value: UNCHANGED, label: "Leave unchanged" },
      { value: CLEAR, label: "Clear timeline intent" },
      ...timelineIntents.map((t) => ({ value: t.id, label: t.name })),
    ],
    [timelineIntents],
  );

  const teamOptions = React.useMemo(
    () => [
      { value: UNCHANGED, label: "Leave unchanged" },
      { value: TEAM_NONE, label: "Clear team" },
      ...teams.map((t) => ({
        value: teamSlugFor(t),
        label: formatTeamLabelForUi(t.name),
      })),
    ],
    [teams],
  );

  const bulkEditTriggerClassName =
    "h-10 min-h-10 rounded-xl bg-gray-50 border-gray-200 text-[13px] font-semibold";

  return (
    <div className={cn("flex flex-col gap-4", className)}>
      <div className="space-y-1.5">
        <label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca']">
          Lead status
        </label>
        <ReactSelect
          value={leadStatusSelectValue}
          onValueChange={(val) => {
            if (val === UNCHANGED) {
              onChange({ ...value, leadStatusTouched: false, leadStatus: "" });
            } else if (val === CLEAR) {
              onChange({ ...value, leadStatusTouched: true, leadStatus: "" });
            } else {
              onChange({ ...value, leadStatusTouched: true, leadStatus: val });
            }
          }}
          options={leadStatusOptions}
          placeholder="Leave unchanged"
          triggerClassName={bulkEditTriggerClassName}
        />
      </div>

      <div className="space-y-1.5">
        <label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca']">
          Brand
        </label>
        <ReactSelect
          value={brandSelectValue}
          onValueChange={(val) => {
            if (val === UNCHANGED) {
              onChange({ ...value, brandTouched: false, brand: "" });
            } else if (val === CLEAR) {
              onChange({ ...value, brandTouched: true, brand: "" });
            } else {
              onChange({ ...value, brandTouched: true, brand: val });
            }
          }}
          options={brandOptions}
          placeholder="Leave unchanged"
          triggerClassName={bulkEditTriggerClassName}
        />
      </div>

      <div className="space-y-1.5">
        <label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca']">
          Channel
        </label>
        <ReactSelect
          value={channelSelectValue}
          onValueChange={(val) => {
            if (val === UNCHANGED) {
              onChange({
                ...value,
                leadChannelIdTouched: false,
                leadChannelId: null,
              });
            } else if (val === CLEAR) {
              onChange({
                ...value,
                leadChannelIdTouched: true,
                leadChannelId: null,
              });
            } else {
              onChange({
                ...value,
                leadChannelIdTouched: true,
                leadChannelId: val,
              });
            }
          }}
          options={channelOptions}
          placeholder="Leave unchanged"
          triggerClassName={bulkEditTriggerClassName}
        />
      </div>

      <div className="space-y-1.5">
        <label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca']">
          Timeline Intent
        </label>
        <ReactSelect
          value={timelineIntentSelectValue}
          onValueChange={(val) => {
            if (val === UNCHANGED) {
              onChange({
                ...value,
                timelineIntentTouched: false,
                timelineIntentId: "",
              });
            } else if (val === CLEAR) {
              onChange({
                ...value,
                timelineIntentTouched: true,
                timelineIntentId: "",
              });
            } else {
              onChange({
                ...value,
                timelineIntentTouched: true,
                timelineIntentId: val,
              });
            }
          }}
          options={timelineIntentOptions}
          placeholder="Leave unchanged"
          triggerClassName={bulkEditTriggerClassName}
        />
      </div>

      <div className="space-y-1.5">
        <label className="text-[11px] font-bold uppercase tracking-wider text-gray-500 font-['Lexend_Deca']">
          Team
        </label>
        <ReactSelect
          value={teamSelectValue}
          onValueChange={(val) => {
            if (val === UNCHANGED) {
              onChange({ ...value, teamTouched: false, team: null });
            } else if (val === TEAM_NONE) {
              onChange({ ...value, teamTouched: true, team: null });
            } else {
              onChange({ ...value, teamTouched: true, team: val });
            }
          }}
          options={teamOptions}
          placeholder="Leave unchanged"
          triggerClassName={bulkEditTriggerClassName}
        />
      </div>




      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={() => onChange(emptyBulkEditFieldsValue)}
        className="self-end h-8 text-[12px]"
      >
        Reset all
      </Button>
    </div>
  );
}
