'use client';

import React, { useMemo } 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 { RadioGroup } from '@alga-psa/ui/components/RadioGroup';
import CustomSelect from '@alga-psa/ui/components/CustomSelect';
import { Switch } from '@alga-psa/ui/components/Switch';
import { ServiceCatalogPicker, ServiceCatalogPickerItem } from '../../ServiceCatalogPicker';
import { Plus, X, Package } from 'lucide-react';
import { ReflectionContainer } from '@alga-psa/ui/ui-reflection/ReflectionContainer';
import { TemplateWizardData } from '../TemplateWizard';
import { TemplateServicePreviewSection } from '../TemplateServicePreviewSection';
import { getRecurringAuthoringPreview } from '../../recurringAuthoringPreview';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

interface TemplateFixedFeeServicesStepProps {
  data: TemplateWizardData;
  updateData: (data: Partial<TemplateWizardData>) => void;
}

export function TemplateFixedFeeServicesStep({
  data,
  updateData,
}: TemplateFixedFeeServicesStepProps) {
  const { t } = useTranslation('msp/contracts');
  const cadenceOwnerOptions = useMemo(() => ([
    {
      value: 'client',
      label: t('templateFixed.cadenceOwner.client.label', {
        defaultValue: 'Invoice on client billing schedule',
      }),
      description: t('templateFixed.cadenceOwner.client.description', {
        defaultValue:
          'Use the client billing calendar so contracts created from this template stay aligned with the client billing cadence.',
      }),
    },
    {
      value: 'contract',
      label: t('templateFixed.cadenceOwner.contract.label', {
        defaultValue: 'Invoice on contract anniversary',
      }),
      description: t('templateFixed.cadenceOwner.contract.description', {
        defaultValue:
          'Use this contract line anniversary schedule. Contract cadence currently supports monthly, quarterly, semi-annual, and annual recurring billing.',
      }),
    },
  ]), [t]);
  const billingTimingOptions = useMemo(
    () => ([
      {
        value: 'arrears',
        label: t('templateFixed.billingTiming.arrears', {
          defaultValue: 'Arrears - invoice after the period closes',
        }),
      },
      {
        value: 'advance',
        label: t('templateFixed.billingTiming.advance', {
          defaultValue: 'Advance - invoice at the start of the period',
        }),
      },
    ]),
    [t]
  );

  const recurringPreview = getRecurringAuthoringPreview({
    cadenceOwner: data.cadence_owner,
    billingTiming: data.billing_timing,
    billingFrequency: data.billing_frequency,
    enableProration: data.enable_proration,
  }, t);

  const handleAddService = () => {
    updateData({
      fixed_services: [
        ...data.fixed_services,
        { service_id: '', service_name: '', quantity: 1 },
      ],
    });
  };

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

  const handleServiceChange = (index: number, item: ServiceCatalogPickerItem) => {
    const next = [...data.fixed_services];
    next[index] = {
      ...next[index],
      service_id: item.service_id,
      service_name: item.service_name,
    };
    updateData({ fixed_services: next });
  };

  const handleQuantityChange = (index: number, quantity: number) => {
    const next = [...data.fixed_services];
    next[index] = { ...next[index], quantity };
    updateData({ fixed_services: next });
  };

  // Build preview services list
  const previewServices = React.useMemo(() => {
    const items: Array<{
      id: string;
      name: string;
      quantity?: number;
      serviceId: string;
    }> = [];

    // Add individual services
    for (const service of data.fixed_services) {
      if (service.service_id) {
        items.push({
          id: `service-${service.service_id}`,
          name:
            service.service_name ||
            t('templateFixed.preview.unknownService', { defaultValue: 'Unknown Service' }),
          quantity: service.quantity ?? 1,
          serviceId: service.service_id,
        });
      }
    }

    return items;
  }, [data.fixed_services, t]);

  const handlePreviewQuantityChange = (itemId: string, quantity: number) => {
    if (itemId.startsWith('service-')) {
      const serviceId = itemId.replace('service-', '');
      const serviceIndex = data.fixed_services.findIndex((s) => s.service_id === serviceId);
      if (serviceIndex !== -1) {
        handleQuantityChange(serviceIndex, quantity);
      }
    }
  };

  const handlePreviewRemoveService = (itemId: string) => {
    if (itemId.startsWith('service-')) {
      // Remove individual service
      const serviceId = itemId.replace('service-', '');
      const serviceIndex = data.fixed_services.findIndex((s) => s.service_id === serviceId);
      if (serviceIndex !== -1) {
        handleRemoveService(serviceIndex);
      }
    }
  };

  return (
    <ReflectionContainer id="template-fixed-fee-services-step">
      <div className="space-y-6">
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-2">
            {t('templateFixed.heading', { defaultValue: 'Fixed Fee Services' })}
          </h3>
          <p className="text-sm text-[rgb(var(--color-text-500))]">
            {t('templateFixed.description', {
              defaultValue:
                'Configure services that are billed at a fixed rate each billing cycle. You can still track time, but billing is based on this flat amount.',
            })}
          </p>
        </div>

        <div className="p-4 bg-accent-50 border border-accent-200 rounded-md">
          <p className="text-sm text-accent-900">
            <strong>
              {t('templateFixed.info.title', { defaultValue: 'What are Fixed Fee Services?' })}
            </strong>{' '}
            {t('templateFixed.info.description', {
              defaultValue:
                "These services have a set recurring price. You'll still track time entries for these services, but billing is based on the fixed rate, not hours worked.",
            })}
          </p>
        </div>

        <div className="space-y-3">
          <div>
            <Label className="text-sm font-medium">
              {t('templateFixed.cadenceOwner.label', { defaultValue: 'Cadence Owner' })}
            </Label>
            <p className="text-xs text-[rgb(var(--color-text-400))] mt-1">
              {t('templateFixed.cadenceOwner.help', {
                defaultValue:
                  'Choose which schedule should define recurring service periods for contracts created from this template.',
              })}
            </p>
          </div>
          <RadioGroup
            id="template-wizard-cadence-owner"
            name="template-wizard-cadence-owner"
            options={cadenceOwnerOptions}
            value={data.cadence_owner ?? 'client'}
            onChange={(value) =>
              updateData({ cadence_owner: value as TemplateWizardData['cadence_owner'] })
            }
          />
        </div>

        <div className="grid gap-4 md:grid-cols-2">
          <div className="space-y-2">
            <Label htmlFor="template-fixed-billing-timing" className="text-sm font-medium">
              {t('templateFixed.fields.billingTiming', { defaultValue: 'Billing Timing' })}
            </Label>
            <CustomSelect
              id="template-fixed-billing-timing"
              value={data.billing_timing ?? 'arrears'}
              onValueChange={(value) =>
                updateData({ billing_timing: value as TemplateWizardData['billing_timing'] })
              }
              options={billingTimingOptions.map((option) => ({
                value: option.value,
                label: option.label,
              }))}
              placeholder={t('templateFixed.placeholders.billingTiming', {
                defaultValue: 'Select billing timing',
              })}
            />
            <p className="text-xs text-[rgb(var(--color-text-400))]">
              {recurringPreview.firstInvoiceSummary}
            </p>
          </div>

          <div className="border border-[rgb(var(--color-border-200))] rounded-md p-4 bg-[rgb(var(--color-border-50))] space-y-3">
            <div className="flex items-center justify-between">
              <Label htmlFor="template-fixed-enable-proration" className="text-sm font-medium">
                {t('templateFixed.fields.adjustPartialPeriods', {
                  defaultValue: 'Adjust for Partial Periods',
                })}
              </Label>
              <Switch
                id="template-fixed-enable-proration"
                checked={Boolean(data.enable_proration)}
                onCheckedChange={(checked) => updateData({ enable_proration: checked })}
              />
            </div>
            <p className="text-xs text-[rgb(var(--color-text-400))]">
              {t('templateFixed.help.adjustPartialPeriods', {
                defaultValue:
                  'Use this when contracts created from the template should scale the recurring fee if service starts or ends inside a period.',
              })}
            </p>
          </div>
        </div>

        <div className="border border-[rgb(var(--color-border-200))] rounded-md p-4 bg-[rgb(var(--color-border-50))] space-y-2 text-sm">
          <p>
            <strong>{t('templateFixed.preview.cadenceOwnerLabel', { defaultValue: 'Cadence Owner:' })}</strong>{' '}
            {recurringPreview.cadenceOwnerLabel}
          </p>
          <p>{recurringPreview.cadenceOwnerSummary}</p>
          <p>
            <strong>{t('templateFixed.preview.billingTimingLabel', { defaultValue: 'Billing Timing:' })}</strong>{' '}
            {recurringPreview.billingTimingLabel}
          </p>
          <p>{recurringPreview.billingTimingSummary}</p>
          <p>{recurringPreview.partialPeriodSummary}</p>
          <p>
            <strong>{recurringPreview.materializedPeriodsHeading}:</strong>
          </p>
          <p>{recurringPreview.materializedPeriodsSummary}</p>
          <ul className="list-disc pl-5 space-y-1">
            {recurringPreview.materializedPeriods.map((period) => (
              <li key={`${period.servicePeriodLabel}:${period.invoiceWindowLabel}`}>
                <span>
                  <strong>{t('templateFixed.preview.serviceLabel', { defaultValue: 'Service:' })}</strong>{' '}
                  {period.servicePeriodLabel}
                </span>
                <span className="block">
                  <strong>
                    {t('templateFixed.preview.invoiceWindowLabel', { defaultValue: 'Invoice window:' })}
                  </strong>{' '}
                  {period.invoiceWindowLabel}
                </span>
              </li>
            ))}
          </ul>
        </div>

        <TemplateServicePreviewSection
          services={previewServices}
          serviceType="fixed"
          onQuantityChange={handlePreviewQuantityChange}
          onRemoveService={handlePreviewRemoveService}
        />

        <div className="space-y-4">
          <Label className="flex items-center gap-2">
            <Package className="h-4 w-4" />
            {t('templateFixed.fields.services', { defaultValue: 'Services' })}
          </Label>

          {data.fixed_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={`template-fixed-service-${index}`} className="text-sm">
                    {t('templateFixed.fields.serviceNumber', {
                      index: index + 1,
                      defaultValue: 'Service {{index}}',
                    })}
                  </Label>
                  <ServiceCatalogPicker
                    id={`template-fixed-service-${index}`}
                    value={service.service_id}
                    selectedLabel={service.service_name}
                    onSelect={(item) => handleServiceChange(index, item)}
                    itemKinds={['service']}
                    placeholder={t('templateFixed.placeholders.selectService', {
                      defaultValue: 'Select a service',
                    })}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor={`template-fixed-quantity-${index}`} className="text-sm">
                    {t('templateFixed.fields.quantityOptional', {
                      defaultValue: 'Quantity (Optional)',
                    })}
                  </Label>
                  <Input
                    id={`template-fixed-quantity-${index}`}
                    type="number"
                    min="1"
                    value={service.quantity ?? 1}
                    onChange={(event) =>
                      handleQuantityChange(index, Math.max(1, Number(event.target.value) || 1))
                    }
                    className="w-24"
                  />
                  <p className="text-xs text-[rgb(var(--color-text-400))]">
                    {t('templateFixed.help.quantity', {
                      defaultValue: 'Suggested quantity when creating contracts',
                    })}
                  </p>
                </div>
              </div>

              <Button
                id={`template-fixed-remove-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="template-fixed-add-service"
            type="button"
            variant="secondary"
            onClick={handleAddService}
            className="inline-flex items-center gap-2"
          >
            <Plus className="h-4 w-4" />
            {t('templateFixed.actions.addService', { defaultValue: 'Add Service' })}
          </Button>
        </div>
      </div>
    </ReflectionContainer>
  );
}
