'use client';

import React from 'react';
import { BucketOverlayInput, TemplateWizardData } from '../TemplateWizard';
import { Label } from '@alga-psa/ui/components/Label';
import { ServiceCatalogPicker, ServiceCatalogPickerItem } from '../../ServiceCatalogPicker';
import { Button } from '@alga-psa/ui/components/Button';
import { Input } from '@alga-psa/ui/components/Input';
import { ReflectionContainer } from '@alga-psa/ui/ui-reflection/ReflectionContainer';
import { Plus, X, Activity } from 'lucide-react';
import { TemplateServicePreviewSection } from '../TemplateServicePreviewSection';
import { SwitchWithLabel } from '@alga-psa/ui/components/SwitchWithLabel';
import { BucketOverlayFields } from '../../BucketOverlayFields';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

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

export function TemplateHourlyServicesStep({
  data,
  updateData,
}: TemplateHourlyServicesStepProps) {
  const { t } = useTranslation('msp/contracts');

  const handleAddService = () => {
    updateData({
      hourly_services: [
        ...data.hourly_services,
        { service_id: '', service_name: '', bucket_overlay: undefined },
      ],
    });
  };

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

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

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

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

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

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

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

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

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

  return (
    <ReflectionContainer id="template-hourly-services-step">
      <div className="space-y-6">
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-2">
            {t('templateHourly.heading', { defaultValue: 'Hourly Services' })}
          </h3>
          <p className="text-sm text-[rgb(var(--color-text-500))]">
            {t('templateHourly.description', {
              defaultValue:
                "Select services that are billed based on time tracked. Rates will be determined by the service's pricing in the client's currency when the contract is created.",
            })}
          </p>
        </div>

        <div className="p-4 bg-accent-50 border border-accent-200 rounded-md mb-6">
          <p className="text-sm text-accent-900">
            <strong>
              {t('templateHourly.info.title', { defaultValue: 'What are Hourly Services?' })}
            </strong>{' '}
            {t('templateHourly.info.description', {
              defaultValue:
                "These services are billed based on actual time tracked. Each time entry will be multiplied by the service's hourly rate to calculate the invoice amount.",
            })}
          </p>
        </div>

        <TemplateServicePreviewSection
          services={previewServices}
          serviceType="hourly"
          onRemoveService={handlePreviewRemoveService}
        />

        {/* Time rounding settings - shown once if any hourly services are added */}
        {data.hourly_services.length > 0 && (
          <div className="p-4 border border-[rgb(var(--color-border-200))] rounded-md bg-[rgb(var(--color-border-50))]">
            <h4 className="text-sm font-medium mb-3">
              {t('templateHourly.rounding.heading', { defaultValue: 'Time Rounding Settings' })}
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="template-min-time" className="text-sm">
                  {t('templateHourly.rounding.minimumBillableTime', {
                    defaultValue: 'Minimum Billable Time (minutes)',
                  })}
                </Label>
                <Input
                  id="template-min-time"
                  type="number"
                  min="0"
                  value={data.minimum_billable_time ?? ''}
                  onChange={(event) =>
                    updateData({
                      minimum_billable_time: Math.max(
                        0,
                        Number(event.target.value) || 0
                      ),
                    })
                  }
                  placeholder={t('templateHourly.rounding.defaultIntervalPlaceholder', {
                    defaultValue: '15',
                  })}
                />
                <p className="text-xs text-[rgb(var(--color-text-400))]">
                  {t('templateHourly.rounding.minimumBillableTimeHelp', {
                    defaultValue:
                      'Example: 15 minutes. Any time entry below this threshold is rounded up.',
                  })}
                </p>
              </div>
              <div className="space-y-2">
                <Label htmlFor="template-round-up" className="text-sm">
                  {t('templateHourly.rounding.roundUpToNearest', {
                    defaultValue: 'Round Up To Nearest (minutes)',
                  })}
                </Label>
                <Input
                  id="template-round-up"
                  type="number"
                  min="0"
                  value={data.round_up_to_nearest ?? ''}
                  onChange={(event) =>
                    updateData({
                      round_up_to_nearest: Math.max(
                        0,
                        Number(event.target.value) || 0
                      ),
                    })
                  }
                  placeholder={t('templateHourly.rounding.defaultIntervalPlaceholder', {
                    defaultValue: '15',
                  })}
                />
                <p className="text-xs text-[rgb(var(--color-text-400))]">
                  {t('templateHourly.rounding.roundUpToNearestHelp', {
                    defaultValue:
                      'Example: 15 minutes. Time entries are rounded up to the nearest interval.',
                  })}
                </p>
              </div>
            </div>
          </div>
        )}

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

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

                <div className="space-y-3 pt-2 border-t border-dashed border-blue-100">
                  <SwitchWithLabel
                    label={t('templateHourly.fields.setBucketOfHours', {
                      defaultValue: 'Set bucket of hours',
                    })}
                    checked={Boolean(service.bucket_overlay)}
                    onCheckedChange={(checked) => toggleBucketOverlay(index, Boolean(checked))}
                  />
                  {service.bucket_overlay && (
                    <BucketOverlayFields
                      mode="hours"
                      value={service.bucket_overlay ?? defaultOverlay(data.billing_frequency)}
                      onChange={(next) => updateBucketOverlay(index, next)}
                      automationId={`template-hourly-bucket-${index}`}
                      billingFrequency={data.billing_frequency}
                    />
                  )}
                </div>
              </div>

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