'use client';

import { ToggleLeft, ToggleRight } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { SystemSetting } from '@/lib/api';
import { getSettingMeta } from '@/lib/system-settings-catalog';

function parseBoolean(value: string) {
  return ['true', '1', 'yes'].includes(value.trim().toLowerCase());
}

interface SettingsFieldRowProps {
  setting: SystemSetting;
  onChange: (value: string) => void;
}

export function SettingsFieldRow({ setting, onChange }: SettingsFieldRowProps) {
  const meta = getSettingMeta(setting.key);
  const label = meta?.label ?? setting.key;
  const type = meta?.type ?? 'text';

  return (
    <div className="flex flex-col gap-3 border-b border-[#e8eaef] py-4 last:border-b-0 last:pb-0 first:pt-0 md:flex-row md:items-center md:justify-between">
      <div className="min-w-0 flex-1">
        <div className="font-semibold">{label}</div>
        <p className="mt-1 text-sm text-[#667085]">{meta?.hint ?? setting.description ?? setting.key}</p>
      </div>

      <div className="flex w-full shrink-0 items-center gap-2 md:w-auto">
        {type === 'boolean' ? (
          <button
            type="button"
            aria-label={label}
            onClick={() => onChange(parseBoolean(setting.value) ? 'false' : 'true')}
          >
            {parseBoolean(setting.value) ? (
              <ToggleRight className="h-9 w-9 text-green-600" />
            ) : (
              <ToggleLeft className="h-9 w-9 text-[#a8adbc]" />
            )}
          </button>
        ) : type === 'select' ? (
          <select
            className="h-10 w-full min-w-0 rounded-xl border border-[#e4e7ec] bg-white px-3 text-sm outline-none focus:border-[#98a2b3] md:min-w-[220px] md:w-auto"
            value={setting.value}
            onChange={(event) => onChange(event.target.value)}
          >
            {(meta?.options ?? []).map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        ) : type === 'textarea' ? (
          <textarea
            value={setting.value}
            rows={3}
            className="min-h-[88px] w-full min-w-0 resize-y rounded-xl border border-[#e4e7ec] bg-white px-3 py-2 text-sm outline-none focus:border-[#98a2b3] md:w-[360px]"
            onChange={(event) => onChange(event.target.value)}
          />
        ) : (
          <>
            <Input
              type={setting.isSecret ? 'password' : type === 'number' ? 'number' : 'text'}
              value={setting.value}
              className={setting.isSecret ? 'w-full min-w-0 bg-white md:w-[280px]' : 'w-full min-w-0 bg-white md:w-[220px]'}
              onChange={(event) => onChange(event.target.value)}
            />
            {meta?.unit ? <span className="text-sm text-[#667085]">{meta.unit}</span> : null}
          </>
        )}
      </div>
    </div>
  );
}
