"use client";

import { SearchableSelect } from "@/components/searchable-select/searchable-select";
import { Select } from "@/components/select";
import type { Habit } from "@/features/habits/types";
import type { Task } from "@/features/tasks/types";
import { goalsDict } from "@/features/goals/dict";
import type {
  GoalContribution,
  GoalSourceFormRow,
  GoalSourceType,
} from "@/features/goals/types";
import { createEmptySourceRow } from "@/features/goals/utils/goal-helpers";

type GoalSourcesEditorProps = {
  sources: GoalSourceFormRow[];
  habits: Habit[];
  tasks: Task[];
  onChange: (sources: GoalSourceFormRow[]) => void;
};

const sourceTypeOptions = Object.keys(goalsDict.sourceTypes) as GoalSourceType[];
const contributionOptions = Object.keys(goalsDict.contributions) as GoalContribution[];

export function GoalSourcesEditor({
  sources,
  habits,
  tasks,
  onChange,
}: GoalSourcesEditorProps) {
  const updateSource = (clientId: string, patch: Partial<GoalSourceFormRow>) => {
    onChange(
      sources.map((source) =>
        source.clientId === clientId ? { ...source, ...patch } : source,
      ),
    );
  };

  const removeSource = (clientId: string) => {
    onChange(sources.filter((source) => source.clientId !== clientId));
  };

  const addSource = () => {
    onChange([...sources, createEmptySourceRow()]);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-sm font-medium">{goalsDict.sourcesLabel}</p>
        <button
          type="button"
          onClick={addSource}
          className="rounded-xl bg-accent px-3 py-1.5 text-xs font-medium text-accent-foreground transition-colors hover:bg-primary/15 hover:text-primary"
        >
          {goalsDict.addSource}
        </button>
      </div>

      {sources.map((source, index) => {
        const habitOptions = habits.map((habit) => ({
          value: habit.id,
          label: habit.name,
          searchText: habit.name,
        }));

        const taskOptions = tasks.map((task) => ({
          value: task.id,
          label: task.title,
          searchText: task.title,
        }));

        const showMinValue = source.contribution === "COUNT_DAYS";
        const showSourcePicker = source.sourceType !== "MANUAL";

        return (
          <div
            key={source.clientId}
            className="space-y-3 rounded-2xl border border-border bg-input/40 p-4"
          >
            <div className="flex items-center justify-between">
              <p className="text-sm font-medium">
                {goalsDict.sourceItemLabel} {(index + 1).toLocaleString("fa-IR")}
              </p>
              {sources.length > 1 ? (
                <button
                  type="button"
                  onClick={() => removeSource(source.clientId)}
                  className="text-xs text-destructive"
                >
                  {goalsDict.delete}
                </button>
              ) : null}
            </div>

            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              <div className="space-y-2">
                <label className="text-xs font-medium text-muted-foreground">
                  {goalsDict.sourceTypeLabel}
                </label>
                <Select
                  selectSize="sm"
                  value={source.sourceType}
                  onChange={(event) =>
                    updateSource(source.clientId, {
                      sourceType: event.target.value as GoalSourceType,
                      sourceId: "",
                    })
                  }
                >
                  {sourceTypeOptions.map((option) => (
                    <option key={option} value={option}>
                      {goalsDict.sourceTypes[option]}
                    </option>
                  ))}
                </Select>
              </div>

              <div className="space-y-2">
                <label className="text-xs font-medium text-muted-foreground">
                  {goalsDict.contributionLabel}
                </label>
                <Select
                  selectSize="sm"
                  value={source.contribution}
                  onChange={(event) =>
                    updateSource(source.clientId, {
                      contribution: event.target.value as GoalContribution,
                    })
                  }
                >
                  {contributionOptions.map((option) => (
                    <option key={option} value={option}>
                      {goalsDict.contributions[option]}
                    </option>
                  ))}
                </Select>
              </div>
            </div>

            {showSourcePicker ? (
              <div className="space-y-2">
                <label className="text-xs font-medium text-muted-foreground">
                  {source.sourceType === "HABIT"
                    ? goalsDict.sourceTypes.HABIT
                    : goalsDict.sourceTypes.TASK}
                </label>
                <SearchableSelect
                  value={source.sourceId}
                  onChange={(sourceId) => updateSource(source.clientId, { sourceId })}
                  options={source.sourceType === "HABIT" ? habitOptions : taskOptions}
                  placeholder={goalsDict.sourceItemLabel}
                />
              </div>
            ) : null}

            {showMinValue ? (
              <div className="space-y-2">
                <label className="text-xs font-medium text-muted-foreground">
                  {goalsDict.minValueLabel}
                </label>
                <input
                  type="number"
                  min={0}
                  dir="ltr"
                  value={source.minValueToCountDay}
                  onChange={(event) =>
                    updateSource(source.clientId, {
                      minValueToCountDay: event.target.value,
                    })
                  }
                  className="h-11 w-full rounded-2xl bg-input px-3 text-sm ring-1 ring-border outline-none focus:ring-2 focus:ring-primary"
                />
              </div>
            ) : null}
          </div>
        );
      })}
    </div>
  );
}
