'use client';

import { useState, useMemo, useEffect } from 'react';
import { Bell } from 'lucide-react';
import { RadioGroup, RadioCard } from '@/components/ui/primitives/RadioGroup';
import { Button } from '@/components/ui/primitives/Button';
import { formatDateTime } from '@/lib/format';
import { pickLocalized } from '@/lib/i18n';
import { useLocale } from '@/lib/i18n/react';
import { useT } from '@/lib/i18n/react';
import type { AxisWithOptions, SkuRow } from '@/server/domain/variants/read';

export interface VariantPickerProps {
  axes: AxisWithOptions[];
  skus: SkuRow[];
  onSelect: (dealSkuId: string | null) => void;
  /** When provided, OOS disabled options show an inline bell affordance. */
  onNotifyOosSku?: (skuId: string) => void;
}

/**
 * VariantPicker — renders one RadioGroup per variant axis.
 * When all axes have a selection, resolves the matching active SKU and calls onSelect.
 */
export function VariantPicker({ axes, skus, onSelect, onNotifyOosSku }: VariantPickerProps) {
  const { locale } = useLocale();
  const t = useT('variants');
  const tBis = useT('back_in_stock');

  // Map of axisId → selected optionId
  const [selected, setSelected] = useState<Record<string, string>>({});

  const activeAxes = useMemo(() => axes.filter((a) => a.isActive), [axes]);

  const matchedSku = useMemo(() => {
    if (Object.keys(selected).length !== activeAxes.length) return null;
    const ids = activeAxes.map((a) => selected[a.id]);
    if (ids.some((id) => !id)) return null;
    const sorted = [...ids].sort();
    return (
      skus.find((s) => s.isActive && [...s.optionIds].sort().join('|') === sorted.join('|')) ?? null
    );
  }, [selected, activeAxes, skus]);

  useEffect(() => {
    onSelect(matchedSku?.id ?? null);
  }, [matchedSku?.id, onSelect]);

  if (activeAxes.length === 0) return null;

  return (
    <div className="flex flex-col gap-5">
      {activeAxes.map((axis) => {
        const axisLabel = pickLocalized(axis, locale);
        const activeOptions = axis.options.filter((o) => o.isActive);

        return (
          <div key={axis.id} className="flex flex-col gap-2">
            <p id={`variant-axis-${axis.id}`} className="text-text-secondary text-sm font-medium">
              {axisLabel}
            </p>
            <RadioGroup
              value={selected[axis.id] ?? ''}
              onValueChange={(value) => setSelected((prev) => ({ ...prev, [axis.id]: value }))}
              aria-labelledby={`variant-axis-${axis.id}`}
              className="flex flex-col gap-2"
            >
              {activeOptions.map((option) => {
                const optionLabel = pickLocalized(option, locale, 'label');

                // Check if this option is part of any available (in-stock + active) SKU
                const hasStock = skus.some(
                  (s) =>
                    s.isActive &&
                    s.optionIds.includes(option.id) &&
                    s.quantityTotal - s.quantitySold > 0,
                );

                // Build timeslot description if applicable
                const description =
                  axis.kind === 'TIMESLOT' && option.slotStart
                    ? formatDateTime(option.slotStart, locale)
                    : undefined;

                const oosSkuId =
                  !hasStock && onNotifyOosSku
                    ? skus.find(
                        (s) =>
                          s.optionIds.includes(option.id) && s.quantityTotal - s.quantitySold <= 0,
                      )?.id
                    : undefined;

                return (
                  <div key={option.id} className="relative">
                    <RadioCard
                      value={option.id}
                      label={optionLabel}
                      description={
                        description ?? (!hasStock ? (t('out_of_stock') as string) : undefined)
                      }
                      disabled={!hasStock}
                      icon={
                        option.swatchHex ? (
                          <span
                            className="h-4 w-4 rounded-full border border-neutral-200"
                            style={{ backgroundColor: option.swatchHex }}
                            aria-hidden
                          />
                        ) : undefined
                      }
                    />
                    {oosSkuId && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute end-2 top-1/2 -translate-y-1/2 text-xs"
                        onClick={() => onNotifyOosSku!(oosSkuId)}
                        aria-label={tBis('notify_me_variant') as string}
                        iconStart={<Bell size={12} aria-hidden="true" />}
                      >
                        {tBis('notify_me_variant')}
                      </Button>
                    )}
                  </div>
                );
              })}
            </RadioGroup>
          </div>
        );
      })}
    </div>
  );
}
