'use client';

import React, { useState, useEffect } from 'react';
import { Label } from '@alga-psa/ui/components/Label';
import { Input } from '@alga-psa/ui/components/Input';
import { Button } from '@alga-psa/ui/components/Button';
import { BucketOverlayInput, ContractWizardData } from '../ContractWizard';
import { ServiceCatalogPicker, ServiceCatalogPickerItem } from '../ServiceCatalogPicker';
import { Plus, X, Activity, Coins } from 'lucide-react';
import { getCurrencySymbol } from '@alga-psa/core';
import { SwitchWithLabel } from '@alga-psa/ui/components/SwitchWithLabel';
import { BucketOverlayFields } from '../BucketOverlayFields';
import { BillingFrequencyOverrideSelect } from '../BillingFrequencyOverrideSelect';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

interface UsageBasedServicesStepProps {
  data: ContractWizardData;
  updateData: (data: Partial<ContractWizardData>) => void;
}

export function UsageBasedServicesStep({ data, updateData }: UsageBasedServicesStepProps) {
  const { t } = useTranslation('msp/contracts');
  const [rateInputs, setRateInputs] = useState<Record<number, string>>({});
  // Legacy default_rate (untagged), shown as a hint when no service_prices row exists for the contract currency.
  const [legacyDefaultRates, setLegacyDefaultRates] = useState<Record<number, number | null>>({});
  const [missingCurrencyPrice, setMissingCurrencyPrice] = useState<Record<number, boolean>>({});

  useEffect(() => {
    const inputs: Record<number, string> = {};
    data.usage_services?.forEach((service, index) => {
      if (service.unit_rate !== undefined) {
        inputs[index] = (service.unit_rate / 100).toFixed(2);
      }
    });
    setRateInputs(inputs);
  }, [data.usage_services]);

  const handleAddService = () => {
    updateData({
      usage_services: [
        ...(data.usage_services ?? []),
        {
          service_id: '',
          service_name: '',
          unit_rate: undefined,
          unit_of_measure: 'unit',
          bucket_overlay: undefined,
        },
      ],
    });
  };

  const handleRemoveService = (index: number) => {
    const next = (data.usage_services ?? []).filter((_, i) => i !== index);
    updateData({ usage_services: next });
  };

  const handleServiceChange = (index: number, item: ServiceCatalogPickerItem) => {
    const next = [...(data.usage_services ?? [])];
    const currencyRate =
      typeof item.currency_rate === 'number' && item.currency_rate > 0
        ? item.currency_rate
        : undefined;
    next[index] = {
      ...next[index],
      service_id: item.service_id,
      service_name: item.service_name,
      // Only prefill when a price exists in the contract's currency. Legacy default_rate is
      // untagged and likely USD — don't paste it into a non-USD contract.
      unit_rate: currencyRate,
      unit_of_measure: item.unit_of_measure || next[index].unit_of_measure || 'unit',
    };
    updateData({ usage_services: next });
    setLegacyDefaultRates((prev) => ({
      ...prev,
      [index]: item.default_rate > 0 ? item.default_rate : null,
    }));
    setMissingCurrencyPrice((prev) => ({ ...prev, [index]: currencyRate === undefined }));
  };

  const handleRateChange = (index: number, cents: number) => {
    const next = [...(data.usage_services ?? [])];
    next[index] = { ...next[index], unit_rate: cents };
    updateData({ usage_services: next });
  };

  const handleUnitChange = (index: number, unit: string) => {
    const next = [...(data.usage_services ?? [])];
    next[index] = { ...next[index], unit_of_measure: unit };
    updateData({ usage_services: next });
  };

  const defaultOverlay = (billingFrequency: string): BucketOverlayInput => ({
    total_minutes: undefined,
    overage_rate: undefined,
    allow_rollover: false,
    billing_period: billingFrequency as 'monthly' | 'weekly',
  });

  const toggleBucketOverlay = (index: number, enabled: boolean) => {
    const next = [...(data.usage_services ?? [])];
    if (enabled) {
      const existing = next[index]?.bucket_overlay;
      const effectiveBillingFrequency = data.usage_billing_frequency ?? data.billing_frequency;
      next[index] = {
        ...next[index],
        bucket_overlay: existing ? { ...existing } : defaultOverlay(effectiveBillingFrequency),
      };
    } else {
      next[index] = { ...next[index], bucket_overlay: undefined };
    }
    updateData({ usage_services: next });
  };

  const updateBucketOverlay = (index: number, overlay: BucketOverlayInput) => {
    const next = [...(data.usage_services ?? [])];
    next[index] = { ...next[index], bucket_overlay: { ...overlay } };
    updateData({ usage_services: next });
  };

  const currencySymbol = getCurrencySymbol(data.currency_code);

  const formatCurrency = (cents: number | undefined) => {
    if (!cents) return `${currencySymbol}0.00`;
    return `${currencySymbol}${(cents / 100).toFixed(2)}`;
  };

  return (
    <div className="space-y-6">
      <div className="mb-6">
        <h3 className="text-lg font-semibold mb-2">
          {t('wizardUsage.heading', { defaultValue: 'Usage-Based Services' })}
        </h3>
        <p className="text-sm text-[rgb(var(--color-text-500))]">
          {t('wizardUsage.description', {
            defaultValue: 'Configure services that are billed based on usage or consumption. Perfect for metered services like data transfer, API calls, or storage.',
          })}
        </p>
      </div>

      <div className="p-4 bg-[rgb(var(--color-accent-50))] border border-[rgb(var(--color-accent-200))] rounded-md mb-6">
        <p className="text-sm text-[rgb(var(--color-accent-800))]">
          <strong>{t('wizardUsage.explainer.title', { defaultValue: 'What are Usage-Based Services?' })}</strong>{' '}
          {t('wizardUsage.explainer.description', {
            defaultValue: 'These services are billed based on actual consumption or usage metrics. Each unit consumed will be multiplied by the unit rate to calculate the invoice amount.',
          })}
        </p>
      </div>

      <div className="space-y-4">
        <Label className="text-sm flex items-center gap-2">
          <Activity className="h-4 w-4" />
          {t('wizardUsage.labels.services', { defaultValue: 'Services' })}
        </Label>

        {(data.usage_services ?? []).map((service, index) => (
          <div
            key={index}
            className="flex items-start gap-3 p-4 border border-[rgb(var(--color-border-200))] rounded-md bg-[rgb(var(--color-border-50))]"
          >
            <div className="flex-1 space-y-3">
              <div className="space-y-2">
                <Label htmlFor={`usage-service-${index}`} className="text-sm">
                  {t('wizardUsage.labels.serviceItem', {
                    defaultValue: 'Service {{index}}',
                    index: index + 1,
                  })}
                </Label>
                <ServiceCatalogPicker
                  id={`usage-service-${index}`}
                  value={service.service_id}
                  selectedLabel={service.service_name}
                  onSelect={(item) => handleServiceChange(index, item)}
                  itemKinds={['service']}
                  currencyCode={data.currency_code}
                  placeholder={t('wizardUsage.labels.selectServicePlaceholder', {
                    defaultValue: 'Select a service',
                  })}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor={`unit-rate-${index}`} className="text-sm flex items-center gap-2 h-5">
                    <Coins className="h-3 w-3" />
                    {t('wizardUsage.labels.ratePerUnit', { defaultValue: 'Rate per Unit' })}
                  </Label>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-[rgb(var(--color-text-400))]">
                      {currencySymbol}
                    </span>
                    <Input
                      id={`unit-rate-${index}`}
                      type="text"
                      inputMode="decimal"
                      value={rateInputs[index] ?? ''}
                      onChange={(event) => {
                        const value = event.target.value.replace(/[^0-9.]/g, '');
                        const decimalCount = (value.match(/\./g) || []).length;
                        if (decimalCount <= 1) {
                          setRateInputs((prev) => ({ ...prev, [index]: value }));
                        }
                      }}
                      onBlur={() => {
                        const inputValue = rateInputs[index] ?? '';
                        if (inputValue.trim() === '' || inputValue === '.') {
                          setRateInputs((prev) => ({ ...prev, [index]: '' }));
                          handleRateChange(index, 0);
                        } else {
                          const dollars = parseFloat(inputValue) || 0;
                          const cents = Math.round(dollars * 100);
                          handleRateChange(index, cents);
                          setRateInputs((prev) => ({ ...prev, [index]: (cents / 100).toFixed(2) }));
                        }
                      }}
                      placeholder={t('wizardUsage.labels.ratePerUnitPlaceholder', { defaultValue: '0.00' })}
                      className="pl-10"
                    />
                  </div>
                  <p className="text-xs text-[rgb(var(--color-text-400))]">
                    {service.unit_rate
                      ? t('wizardUsage.labels.ratePerUnitValue', {
                        defaultValue: '{{rate}}/{{unit}}',
                        rate: formatCurrency(service.unit_rate),
                        unit: service.unit_of_measure || t('wizardUsage.values.defaultUnit', { defaultValue: 'unit' }),
                      })
                      : t('wizardUsage.labels.enterUnitRate', { defaultValue: 'Enter the unit rate' })}
                  </p>
                  {service.service_id && missingCurrencyPrice[index] ? (
                    <p className="text-xs text-amber-700">
                      {legacyDefaultRates[index]
                        ? t('wizardUsage.labels.noCurrencyPriceWithLegacyHint', {
                            defaultValue:
                              'No {{currency}} price in the catalog. Legacy default rate: {{rate}}. Enter a unit rate in {{currency}}.',
                            currency: data.currency_code,
                            rate: ((legacyDefaultRates[index] ?? 0) / 100).toFixed(2),
                          })
                        : t('wizardUsage.labels.noCurrencyPriceEnterRate', {
                            defaultValue:
                              'No {{currency}} price in the catalog. Enter a unit rate.',
                            currency: data.currency_code,
                          })}
                    </p>
                  ) : null}
                </div>

                <div className="space-y-2">
                  <Label htmlFor={`unit-measure-${index}`} className="text-sm flex items-center gap-2 h-5">
                    {t('wizardUsage.labels.unitOfMeasure', { defaultValue: 'Unit of Measure' })}
                  </Label>
                  <Input
                    id={`unit-measure-${index}`}
                    type="text"
                    value={service.unit_of_measure ?? 'unit'}
                    onChange={(event) => handleUnitChange(index, event.target.value)}
                    placeholder={t('wizardUsage.labels.unitOfMeasurePlaceholder', {
                      defaultValue: 'e.g., GB, API call, user',
                    })}
                  />
                  <p className="text-xs text-[rgb(var(--color-text-400))]">
                    {t('wizardUsage.labels.unitOfMeasureHint', { defaultValue: 'Choose the unit this service bills on.' })}
                  </p>
                </div>
              </div>

              <div className="space-y-3 pt-2 border-t border-dashed border-blue-100">
                <SwitchWithLabel
                  label={t('wizardUsage.labels.setBucketAllocation', { defaultValue: 'Set bucket allocation' })}
                  checked={Boolean(service.bucket_overlay)}
                  onCheckedChange={(checked) => toggleBucketOverlay(index, Boolean(checked))}
                />
                {service.bucket_overlay && (
                  <BucketOverlayFields
                    mode="usage"
                    unitLabel={service.unit_of_measure}
                    value={service.bucket_overlay ?? defaultOverlay(data.usage_billing_frequency ?? data.billing_frequency)}
                    onChange={(next) => updateBucketOverlay(index, next)}
                    automationId={`usage-bucket-${index}`}
                    billingFrequency={data.usage_billing_frequency ?? data.billing_frequency}
                  />
                )}
              </div>
            </div>

            <Button
              id={`remove-usage-service-${index}`}
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => handleRemoveService(index)}
              className="mt-8 text-[rgb(var(--color-destructive))] hover:text-[rgb(var(--color-destructive))] hover:bg-[rgb(var(--color-destructive)/0.1)]"
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
        ))}

        <Button
          id="add-usage-service-button"
          type="button"
          variant="outline"
          onClick={handleAddService}
          className="w-full"
        >
          <Plus className="h-4 w-4 mr-2" />
          {t('wizardUsage.actions.addUsageBasedService', { defaultValue: 'Add Usage-Based Service' })}
        </Button>
      </div>

      {(data.usage_services?.length ?? 0) === 0 && (
        <div className="p-4 bg-[rgb(var(--color-border-50))] border border-[rgb(var(--color-border-200))] rounded-md">
          <p className="text-sm text-[rgb(var(--color-text-500))] text-center">
            {t('wizardUsage.emptyState', {
              defaultValue: 'No usage-based services added yet. Click “Add Usage-Based Service” above or “Skip” if you don’t need consumption billing.',
            })}
          </p>
        </div>
      )}

      {(data.usage_services?.length ?? 0) > 0 && (
        <Alert variant="info" className="mt-6">
          <AlertDescription>
            <h4 className="text-sm font-semibold mb-2">
              {t('wizardUsage.summary.title', { defaultValue: 'Usage-Based Summary' })}
            </h4>
            <div className="text-sm space-y-1">
              <p>
                <strong>{t('wizardUsage.summary.labels.services', { defaultValue: 'Services:' })}</strong>{' '}
                {data.usage_services?.length ?? 0}
              </p>
              <div className="mt-2 space-y-1">
                {data.usage_services?.map(
                  (service, idx) =>
                    service.unit_rate && (
                      <p key={idx} className="text-xs">
                        • {service.service_name || t('wizardUsage.labels.serviceItem', {
                          defaultValue: 'Service {{index}}',
                          index: idx + 1,
                        })}: {t('wizardUsage.labels.ratePerUnitValue', {
                          defaultValue: '{{rate}}/{{unit}}',
                          rate: formatCurrency(service.unit_rate),
                          unit: service.unit_of_measure || t('wizardUsage.values.defaultUnit', { defaultValue: 'unit' }),
                        })}
                      </p>
                    )
                )}
              </div>
            </div>
          </AlertDescription>
        </Alert>
      )}

      {(data.usage_services?.length ?? 0) > 0 && (
        <BillingFrequencyOverrideSelect
          contractBillingFrequency={data.billing_frequency}
          value={data.usage_billing_frequency}
          onChange={(value) => updateData({ usage_billing_frequency: value })}
          label={t('wizardUsage.alternateFrequencyLabel', { defaultValue: 'Alternate Billing Frequency (Optional)' })}
        />
      )}
    </div>
  );
}
