'use client';

import { Controller, useWatch, type Control, type UseFormReturn } from 'react-hook-form';
import { useQuery } from '@tanstack/react-query';
import { NumberInput } from '@/components/ui/primitives/NumberInput';
import { Pill } from '@/components/ui/primitives/Pill';
import { RadioGroup, RadioItem } from '@/components/ui/primitives/RadioGroup';
import { PickupAddressSelector } from '@/components/ui/domain/PickupAddressSelector';
import { useT } from '@/lib/i18n/react';
import type { AddDealFormValues } from '../useAddDeal';
import type { ShippingMode } from '@/lib/enums/shipping-mode';

interface ShippingConfigStepProps {
  form: UseFormReturn<AddDealFormValues>;
}

type CarrierValue = 'wolt_drive' | null;

export function ShippingConfigStep({ form }: ShippingConfigStepProps) {
  const t = useT('vendor_shipping');
  const { watch } = form;

  // Cast needed until Wave 4 adds these fields to AddDealFormValues

  const formAny = form as unknown as UseFormReturn<Record<string, unknown>>;
  const preferredCarrier = (useWatch({ control: formAny.control, name: 'preferredCarrier' }) ??
    null) as CarrierValue;
  const shippingMode = (useWatch({ control: formAny.control, name: 'shippingMode' }) ??
    'free') as ShippingMode;
  const pickupEnabled = (useWatch({ control: formAny.control, name: 'pickupEnabled' }) ??
    false) as boolean;
  const pickupAddressId = (useWatch({ control: formAny.control, name: 'pickupAddressId' }) ??
    null) as string | null;

  const watchAny = watch as unknown as (name: string) => unknown;
  const originalPrice = watchAny('originalPrice') as string | undefined;
  const discountPercent = (watchAny('discountPercent') as number | undefined) ?? 0;
  // Form stores shekels (user input); ×100 to agorot conversion happens in useAddDealActions before API call
  const flatShekels = (watchAny('shippingFlatAgorot') as number | undefined) ?? 0;

  // Compute anti-abuse hint (server enforces the real check)
  const discountedPriceShekels =
    originalPrice && discountPercent
      ? (parseFloat(originalPrice) * (100 - discountPercent)) / 100
      : null;

  const exceedsPrice =
    discountedPriceShekels != null && flatShekels > 0 && flatShekels > discountedPriceShekels;

  const { data: vendorProfile } = useQuery<{ selfPickup?: boolean | null }>({
    queryKey: ['vendor-profile'],
    queryFn: async () => {
      const res = await fetch('/api/vendor/profile', { credentials: 'same-origin' });
      if (!res.ok) throw new Error('Failed');
      const json = (await res.json()) as { ok: boolean; vendor?: { selfPickup?: boolean | null } };
      return json.vendor ?? {};
    },
    staleTime: 30_000,
  });
  const selfPickup = vendorProfile?.selfPickup ?? false;

  const carrierValue = pickupEnabled ? 'pickup' : (preferredCarrier ?? 'manual');

  const controlAny = formAny.control as unknown as Control<AddDealFormValues>;
  return (
    <section className="flex flex-col gap-3 rounded-lg border p-4">
      <h3 className="text-sm font-semibold">{t('shipping_config_title')}</h3>

      {/* Provider picker */}
      <fieldset className="flex flex-col gap-2">
        <legend className="sr-only">{t('shipping_carrier_legend')}</legend>
        <Controller
          name={'preferredCarrier' as keyof AddDealFormValues}
          control={controlAny}
          render={({ field }) => (
            <RadioGroup
              value={carrierValue}
              onValueChange={(v) => {
                if (v === 'pickup') {
                  field.onChange(null);
                  formAny.setValue('pickupEnabled', true);
                } else {
                  field.onChange(v === 'manual' ? null : v);
                  formAny.setValue('pickupEnabled', false);
                  formAny.setValue('pickupAddressId', null);
                }
              }}
            >
              <RadioItem id="carrier-manual" value="manual" label={t('provider_manual')} />
              <RadioItem id="carrier-wolt" value="wolt_drive" label={t('provider_wolt_drive')} />
              <RadioItem
                id="carrier-pickup"
                value="pickup"
                label={t('provider_pickup')}
                disabled={!selfPickup}
              />
            </RadioGroup>
          )}
        />
        {preferredCarrier === 'wolt_drive' && (
          <p className="text-text-muted ms-6 text-xs">{t('provider_wolt_description')}</p>
        )}
        {pickupEnabled && (
          <div className="ms-6 mt-2 flex flex-col gap-2">
            {!selfPickup && (
              <p className="text-text-secondary text-xs">{t('pickup_disabled_hint')}</p>
            )}
            {selfPickup && (
              <PickupAddressSelector
                value={pickupAddressId ?? ''}
                onChange={() => undefined}
                onChangeWithId={(id) => {
                  formAny.setValue('pickupAddressId', id, { shouldValidate: true });
                }}
              />
            )}
            {selfPickup && !pickupAddressId && (
              <p className="text-danger-600 text-xs">{t('pickup_address_required')}</p>
            )}
          </div>
        )}
      </fieldset>

      {/* Buyer shipping fee */}
      <fieldset className="flex flex-col gap-2">
        <legend className="text-sm font-medium">{t('shipping_fee_legend')}</legend>
        <Controller
          name={'shippingMode' as keyof AddDealFormValues}
          control={controlAny}
          render={({ field }) => (
            <RadioGroup
              value={(field.value as ShippingMode | undefined) ?? 'free'}
              onValueChange={(v) => field.onChange(v)}
            >
              <div className="flex flex-wrap items-center gap-2">
                <RadioItem id="ship-mode-free" value="free" label={t('fee_free')} />
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <RadioItem id="ship-mode-flat" value="flat" label={t('fee_flat')} />
                {shippingMode === 'flat' && (
                  <div className="flex items-center gap-1">
                    <Controller
                      name={'shippingFlatAgorot' as keyof AddDealFormValues}
                      control={controlAny}
                      render={({ field }) => (
                        <NumberInput
                          min={0}
                          max={999}
                          step={1}
                          dir="ltr"
                          className="w-20"
                          invalid={exceedsPrice}
                          value={(field.value as number | undefined) ?? 0}
                          onChange={(n) => field.onChange(n)}
                          aria-label={t('fee_flat_amount_label')}
                        />
                      )}
                    />
                    <span className="text-sm">₪</span>
                  </div>
                )}
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <RadioItem
                  id="ship-mode-free-over"
                  value="free_over_threshold"
                  label={t('fee_free_over')}
                />
                {shippingMode === 'free_over_threshold' && (
                  <div className="flex items-center gap-1">
                    <Controller
                      name={'shippingFreeThresholdAgorot' as keyof AddDealFormValues}
                      control={controlAny}
                      render={({ field }) => (
                        <NumberInput
                          min={0}
                          step={1}
                          dir="ltr"
                          className="w-24"
                          value={(field.value as number | undefined) ?? 0}
                          onChange={(n) => field.onChange(n)}
                          aria-label={t('fee_free_over_amount_label')}
                        />
                      )}
                    />
                    <span className="text-sm">₪</span>
                  </div>
                )}
              </div>
            </RadioGroup>
          )}
        />
        {exceedsPrice && (
          <Pill tone="danger" size="sm" role="alert">
            {t('fee_exceeds_price')}
          </Pill>
        )}
        <p className="text-text-muted text-xs">{t('fee_platform_note')}</p>
      </fieldset>
    </section>
  );
}
