'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  createDefaultTaxSettings,
  getClientTaxExemptStatus,
  getClientTaxSettings,
  getTaxRates,
  updateClientTaxExemptStatus,
  updateClientTaxSettings,
} from '@alga-psa/billing/actions/taxSettingsActions';
import { canClientOverrideTaxSource, getEffectiveTaxSourceForClient } from '@alga-psa/billing/actions/taxSourceActions';
import type { TaxSource } from '@alga-psa/types';
import { IClientTaxSettings, ITaxRate, ITaxComponent, ITaxRateThreshold, ITaxHoliday } from '@alga-psa/types';
import CustomSelect from '@alga-psa/ui/components/CustomSelect';
import { Button } from '@alga-psa/ui/components/Button';
import { Input } from '@alga-psa/ui/components/Input';
import { Switch } from '@alga-psa/ui/components/Switch';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@alga-psa/ui/components/Card';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import { ShieldOff, ShieldCheck, Info } from 'lucide-react';
import { Tooltip } from '@alga-psa/ui/components/Tooltip';
import LoadingIndicator from '@alga-psa/ui/components/LoadingIndicator';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

interface TaxSettingsFormProps {
  clientId: string;
}

const TaxSettingsForm: React.FC<TaxSettingsFormProps> = ({ clientId }) => {
  const { t } = useTranslation('msp/billing-settings');
  const [taxSettings, setTaxSettings] = useState<Omit<IClientTaxSettings, 'tenant'> | null>(null);
  const [originalSettings, setOriginalSettings] = useState<Omit<IClientTaxSettings, 'tenant'> | null>(null);
  const [taxRates, setTaxRates] = useState<ITaxRate[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Tax exempt state
  const [isTaxExempt, setIsTaxExempt] = useState(false);
  const [taxExemptionCertificate, setTaxExemptionCertificate] = useState('');
  const [originalTaxExempt, setOriginalTaxExempt] = useState(false);
  const [originalCertificate, setOriginalCertificate] = useState('');
  const [isUpdatingExemptStatus, setIsUpdatingExemptStatus] = useState(false);

  // Tax source override state
  const [canOverrideTaxSource, setCanOverrideTaxSource] = useState(false);
  const [effectiveTaxSource, setEffectiveTaxSource] = useState<TaxSource>('internal');

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [settings, rates, taxExemptStatus, overrideAllowed, effectiveSource] = await Promise.all([
          getClientTaxSettings(clientId),
          getTaxRates(),
          getClientTaxExemptStatus(clientId),
          canClientOverrideTaxSource(),
          getEffectiveTaxSourceForClient(clientId)
        ]);

        // Automatically create default tax settings when none exist
        if (!settings) {
          try {
            const defaultSettings = await createDefaultTaxSettings(clientId);
            setTaxSettings(defaultSettings);
            setOriginalSettings(JSON.parse(JSON.stringify(defaultSettings)));
            setSuccessMessage(t('clientTaxSettings.messages.defaultCreated', {
              defaultValue: 'Default tax settings created successfully'
            }));
          } catch (createErr) {
            setError(t('clientTaxSettings.messages.createDefaultError', {
              defaultValue: 'Error creating default tax settings'
            }));
            setLoading(false);
            return;
          }
        } else {
          setTaxSettings(settings);
          // Store original settings for reverting on error
          setOriginalSettings(JSON.parse(JSON.stringify(settings)));
        }

        setTaxRates(rates);

        // Set tax exempt status
        if (taxExemptStatus) {
          setIsTaxExempt(taxExemptStatus.is_tax_exempt);
          setTaxExemptionCertificate(taxExemptStatus.tax_exemption_certificate || '');
          setOriginalTaxExempt(taxExemptStatus.is_tax_exempt);
          setOriginalCertificate(taxExemptStatus.tax_exemption_certificate || '');
        }

        // Set tax source override state
        setCanOverrideTaxSource(overrideAllowed);
        setEffectiveTaxSource(effectiveSource.taxSource);

        setLoading(false);
      } catch (err) {
        setError(t('clientTaxSettings.messages.fetchError', {
          defaultValue: 'Error fetching tax settings'
        }));
        setLoading(false);
      }
    };

    fetchData();
  }, [clientId, t]);

  // Handle creation of default tax settings when none exist
  const handleCreateDefaultSettings = async () => {
    try {
      setLoading(true);
      const defaultSettings = await createDefaultTaxSettings(clientId);
      setTaxSettings(defaultSettings);
      setError(null);
      setSuccessMessage(t('clientTaxSettings.messages.defaultCreated', {
        defaultValue: 'Default tax settings created successfully'
      }));
      setLoading(false);
    } catch (err) {
      setError(t('clientTaxSettings.messages.createDefaultError', {
        defaultValue: 'Error creating default tax settings'
      }));
      setLoading(false);
    }
  };

  // Dismiss error message
  const dismissError = () => {
    setError(null);
  };

  // Validate tax settings before submission
  const validateTaxSettings = (settings: Omit<IClientTaxSettings, 'tenant'>): string | null => {
   // Removed validation for tax_rate_id as it's no longer part of settings

    // Validate tax rate thresholds
    if (settings.tax_rate_thresholds && settings.tax_rate_thresholds.length > 0) {
      for (let i = 0; i < settings.tax_rate_thresholds.length; i++) {
        const threshold = settings.tax_rate_thresholds[i];
        if (threshold.min_amount < 0) {
          return t('clientTaxSettings.validation.thresholdNegativeMin', {
            index: i + 1,
            defaultValue: 'Threshold {{index}} has a negative minimum amount'
          });
        }
        if (threshold.max_amount !== undefined && threshold.max_amount < threshold.min_amount) {
          return t('clientTaxSettings.validation.thresholdMaxLessThanMin', {
            index: i + 1,
            defaultValue: 'Threshold {{index}} has a maximum amount less than its minimum amount'
          });
        }
        if (threshold.rate < 0) {
          return t('clientTaxSettings.validation.thresholdNegativeRate', {
            index: i + 1,
            defaultValue: 'Threshold {{index}} has a negative rate'
          });
        }
      }
    }

    // Validate tax holidays
    if (settings.tax_holidays && settings.tax_holidays.length > 0) {
      for (let i = 0; i < settings.tax_holidays.length; i++) {
        const holiday = settings.tax_holidays[i];
        if (!holiday.start_date || !holiday.end_date) {
          return t('clientTaxSettings.validation.holidayMissingDates', {
            index: i + 1,
            defaultValue: 'Holiday {{index}} is missing start or end date'
          });
        }
        if (new Date(holiday.start_date) > new Date(holiday.end_date)) {
          return t('clientTaxSettings.validation.holidayEndBeforeStart', {
            index: i + 1,
            defaultValue: 'Holiday {{index}} has an end date before its start date'
          });
        }
      }
    }

    return null;
  };

  // Dismiss success message
  const dismissSuccess = () => {
    setSuccessMessage(null);
  };

  // Handle tax exempt status update
  const handleTaxExemptUpdate = async () => {
    setIsUpdatingExemptStatus(true);
    setError(null);

    try {
      await updateClientTaxExemptStatus(
        clientId,
        isTaxExempt,
        taxExemptionCertificate || undefined
      );

      // Update original values after successful save
      setOriginalTaxExempt(isTaxExempt);
      setOriginalCertificate(taxExemptionCertificate);
      setSuccessMessage(isTaxExempt
        ? t('clientTaxSettings.messages.taxExemptEnabled', {
            defaultValue: 'Client marked as tax exempt.'
          })
        : t('clientTaxSettings.messages.taxExemptDisabled', {
            defaultValue: 'Tax exempt status removed from client.'
          }));
    } catch (err) {
      // Revert on error
      setIsTaxExempt(originalTaxExempt);
      setTaxExemptionCertificate(originalCertificate);
      setError(err instanceof Error
        ? err.message
        : t('clientTaxSettings.messages.taxExemptUpdateError', {
            defaultValue: 'Failed to update tax exempt status'
          }));
    } finally {
      setIsUpdatingExemptStatus(false);
    }
  };

  // Check if tax exempt settings have changed
  const hasTaxExemptChanges = isTaxExempt !== originalTaxExempt ||
    taxExemptionCertificate !== originalCertificate;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!taxSettings) return;

    // Validate tax settings before submission
    const validationError = validateTaxSettings(taxSettings);
    if (validationError) {
      setError(validationError);
      return;
    }

    setIsSubmitting(true);
    try {
      const updatedSettings = await updateClientTaxSettings(clientId, taxSettings);
      setTaxSettings(updatedSettings);
      // Update original settings after successful update
      setOriginalSettings(JSON.parse(JSON.stringify(updatedSettings)));
      setError(null);
      setSuccessMessage(t('clientTaxSettings.messages.updated', {
        defaultValue: 'Tax settings updated successfully'
      }));
    } catch (err) {
      // Revert to original settings on error
      if (originalSettings) {
        setTaxSettings(JSON.parse(JSON.stringify(originalSettings)));
      }
      setError(err instanceof Error
        ? err.message
        : t('clientTaxSettings.messages.updateError', {
            defaultValue: 'Error updating tax settings'
          }));
    } finally {
      setIsSubmitting(false);
    }
  };

 // Removed handleTaxRateChange as tax_rate_id is no longer managed here

 // Removed handlers for components, thresholds, and holidays as these sections are removed

  if (loading) {
    return (
      <div className="flex items-center justify-center py-8">
        <LoadingIndicator 
          layout="stacked" 
          text={t('clientTaxSettings.loading', { defaultValue: 'Loading tax settings...' })}
          spinnerProps={{ size: 'md' }}
        />
      </div>
    );
  }

  // Dismissible error message
  const ErrorMessage = () => {
    if (!error) return null;
    return (
      <Alert variant="destructive" className="mb-4">
        <AlertDescription className="flex items-start justify-between">
          <p>{error}</p>
          <button
            onClick={dismissError}
            className="ml-4 opacity-70 hover:opacity-100"
            aria-label={t('clientTaxSettings.alerts.dismissError', { defaultValue: 'Dismiss error' })}
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
            </svg>
          </button>
        </AlertDescription>
      </Alert>
    );
  };

  // Dismissible success message
  const SuccessMessage = () => {
    if (!successMessage) return null;
    return (
      <Alert variant="success" className="mb-4">
        <AlertDescription className="flex items-start justify-between">
          <p>{successMessage}</p>
          <button
            onClick={dismissSuccess}
            className="ml-4 opacity-70 hover:opacity-100"
            aria-label={t('clientTaxSettings.alerts.dismissSuccess', {
              defaultValue: 'Dismiss success message'
            })}
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
            </svg>
          </button>
        </AlertDescription>
      </Alert>
    );
  };
  if (!taxSettings) {
    return (
      <div className="text-center">
        <ErrorMessage />
        <p className="mb-4">
          {t('clientTaxSettings.noSettingsFound', {
            defaultValue: 'No tax settings found for this client.'
          })}
        </p>
        <Button
          id="create-default-tax-settings-button"
          onClick={handleCreateDefaultSettings}
          variant="default"
        >
          {t('clientTaxSettings.createDefaultButton', {
            defaultValue: 'Create Default Tax Settings'
          })}
        </Button>
      </div>
    );
  }

 // Removed taxRateOptions as the select dropdown is removed

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold">
        {t('clientTaxSettings.title', { defaultValue: 'Client Tax Settings' })}
      </h2>
      <ErrorMessage />
      <SuccessMessage />

      {/* Tax Exempt Status Card */}
      <Card id="tax-exempt-card">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            {isTaxExempt ? (
              <ShieldOff className="h-5 w-5 text-amber-500" />
            ) : (
              <ShieldCheck className="h-5 w-5 text-green-500" />
            )}
            {t('clientTaxSettings.taxExempt.title', { defaultValue: 'Tax Exempt Status' })}
          </CardTitle>
          <CardDescription>
            {t('clientTaxSettings.taxExempt.description', {
              defaultValue: 'Tax exempt clients will not have taxes applied to their invoices.'
            })}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium">
                {t('clientTaxSettings.taxExempt.label', { defaultValue: 'Tax Exempt' })}
              </span>
              <Tooltip content={t('clientTaxSettings.taxExempt.tooltip', {
                defaultValue: 'When enabled, no taxes will be calculated for this client\'s invoices. Changes are logged for audit purposes.'
              })}>
                <Info className="h-4 w-4 text-muted-foreground cursor-help" />
              </Tooltip>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-sm text-muted-foreground">
                {isTaxExempt
                  ? t('clientTaxSettings.taxExempt.status.exempt', { defaultValue: 'Exempt' })
                  : t('clientTaxSettings.taxExempt.status.notExempt', { defaultValue: 'Not Exempt' })}
              </span>
              <Switch
                checked={isTaxExempt}
                onCheckedChange={setIsTaxExempt}
                disabled={isUpdatingExemptStatus}
              />
            </div>
          </div>

          {isTaxExempt && (
            <div className="space-y-2">
              <label htmlFor="tax-exemption-certificate" className="text-sm font-medium">
                {t('clientTaxSettings.taxExempt.certificate.label', {
                  defaultValue: 'Tax Exemption Certificate Number'
                })}
              </label>
              <Input
                id="tax-exemption-certificate"
                type="text"
                placeholder={t('clientTaxSettings.taxExempt.certificate.placeholder', {
                  defaultValue: 'Enter certificate number (optional)'
                })}
                value={taxExemptionCertificate}
                onChange={(e) => setTaxExemptionCertificate(e.target.value)}
                disabled={isUpdatingExemptStatus}
              />
              <p className="text-xs text-muted-foreground">
                {t('clientTaxSettings.taxExempt.certificate.help', {
                  defaultValue: 'Optional: Store the client\'s tax exemption certificate number for reference.'
                })}
              </p>
            </div>
          )}

          {isTaxExempt && (
            <Alert variant="info" showIcon>
              <AlertDescription>
                <p className="font-medium">
                  {t('clientTaxSettings.taxExempt.alert.title', { defaultValue: 'Tax Exempt Client' })}
                </p>
                <p className="text-sm mt-1">
                  {t('clientTaxSettings.taxExempt.alert.description', {
                    defaultValue: 'This client will not be charged any taxes on invoices. Make sure to keep their exemption certificate on file.'
                  })}
                </p>
              </AlertDescription>
            </Alert>
          )}

          {hasTaxExemptChanges && (
            <div className="flex justify-end gap-2 pt-2">
              <Button
                id="cancel-tax-exempt-changes-button"
                type="button"
                variant="outline"
                size="sm"
                onClick={() => {
                  setIsTaxExempt(originalTaxExempt);
                  setTaxExemptionCertificate(originalCertificate);
                }}
                disabled={isUpdatingExemptStatus}
              >
                {t('clientTaxSettings.taxExempt.actions.cancel', { defaultValue: 'Cancel' })}
              </Button>
              <Button
                id="save-tax-exempt-status-button"
                type="button"
                size="sm"
                onClick={handleTaxExemptUpdate}
                disabled={isUpdatingExemptStatus}
              >
                {isUpdatingExemptStatus
                  ? t('clientTaxSettings.taxExempt.actions.saving', { defaultValue: 'Saving...' })
                  : t('clientTaxSettings.taxExempt.actions.save', { defaultValue: 'Save Tax Exempt Status' })}
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Existing Tax Settings Form */}
      <form onSubmit={handleSubmit} className="space-y-6">
        <Card id="reverse-charge-card">
          <CardHeader>
            <CardTitle>
              {t('clientTaxSettings.advanced.title', { defaultValue: 'Advanced Tax Options' })}
            </CardTitle>
            <CardDescription>
              {t('clientTaxSettings.advanced.description', {
                defaultValue: 'Configure special tax handling for this client.'
              })}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium">
                    {t('clientTaxSettings.advanced.reverseCharge.label', {
                      defaultValue: 'Apply Reverse Charge'
                    })}
                  </span>
                  <Tooltip content={t('clientTaxSettings.advanced.reverseCharge.tooltip', {
                    defaultValue: 'Reverse charge shifts the tax liability from the seller to the buyer. Common in B2B transactions across borders.'
                  })}>
                    <Info className="h-4 w-4 text-muted-foreground cursor-help" />
                  </Tooltip>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-muted-foreground">
                    {taxSettings.is_reverse_charge_applicable
                      ? t('common.statuses.enabled', { defaultValue: 'Enabled' })
                      : t('common.statuses.disabled', { defaultValue: 'Disabled' })}
                  </span>
                  <Switch
                    id="reverseCharge"
                    checked={taxSettings.is_reverse_charge_applicable}
                    onCheckedChange={(checked) =>
                      setTaxSettings({ ...taxSettings, is_reverse_charge_applicable: checked })
                    }
                    disabled={isSubmitting}
                  />
                </div>
              </div>
            </div>

            <div className="border-t border-gray-200 pt-6">
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <label htmlFor="tax-source-override" className="text-sm font-medium">
                    {t('clientTaxSettings.advanced.taxSourceOverride.label', {
                      defaultValue: 'Tax Source Override'
                    })}
                  </label>
                  <Tooltip content={t('clientTaxSettings.advanced.taxSourceOverride.tooltip', {
                    defaultValue: 'Override the tenant default tax source for this client. \'Internal\' uses Alga\'s tax calculation. \'External\' delegates tax calculation to the accounting system when invoices are exported.'
                  })}>
                    <Info className="h-4 w-4 text-muted-foreground cursor-help" />
                  </Tooltip>
                </div>
                <CustomSelect
                  id="tax-source-override"
                  value={!canOverrideTaxSource 
                    ? (effectiveTaxSource === 'pending_external' ? 'external' : effectiveTaxSource)
                    : (taxSettings.tax_source_override || '')
                  }
                  onValueChange={(value) => {
                    const newValue = value === '' ? null : (value as TaxSource);
                    setTaxSettings({ ...taxSettings, tax_source_override: newValue });
                  }}
                  options={[
                    {
                      value: '',
                      label: t('clientTaxSettings.advanced.taxSourceOverride.options.default', {
                        defaultValue: 'Use Tenant Default'
                      })
                    },
                    {
                      value: 'internal',
                      label: t('clientTaxSettings.advanced.taxSourceOverride.options.internal', {
                        defaultValue: 'Alga PSA Calculates Tax'
                      })
                    },
                    {
                      value: 'external',
                      label: t('clientTaxSettings.advanced.taxSourceOverride.options.external', {
                        defaultValue: 'Accounting Package Calculates Tax'
                      })
                    },
                  ]}
                  placeholder={t('clientTaxSettings.advanced.taxSourceOverride.placeholder', {
                    defaultValue: 'Select tax source...'
                  })}
                  disabled={isSubmitting || !canOverrideTaxSource}
                />
                <p className="text-xs text-muted-foreground">
                  {t('clientTaxSettings.advanced.taxSourceOverride.effective.label', {
                    defaultValue: 'Current effective tax source:'
                  })}{' '}
                  <span className="font-medium">
                    {effectiveTaxSource === 'internal'
                      ? t('clientTaxSettings.advanced.taxSourceOverride.options.internal', {
                          defaultValue: 'Alga PSA Calculates Tax'
                        })
                      : effectiveTaxSource === 'external'
                        ? t('clientTaxSettings.advanced.taxSourceOverride.options.external', {
                            defaultValue: 'Accounting Package Calculates Tax'
                          })
                        : t('clientTaxSettings.advanced.taxSourceOverride.effective.pendingExternal', {
                            defaultValue: 'Pending External'
                          })}
                  </span>
                  {taxSettings.tax_source_override && (
                    <span className="ml-1">
                      {t('clientTaxSettings.advanced.taxSourceOverride.effective.overridden', {
                        defaultValue: '(overridden)'
                      })}
                    </span>
                  )}
                </p>
                {!canOverrideTaxSource && (
                  <Alert variant="info" showIcon>
                    <AlertDescription>
                      <p className="text-sm">
                        {t('clientTaxSettings.advanced.taxSourceOverride.notAvailable.messageStart', {
                          defaultValue: 'Tax source override is not available. This feature must be enabled in the'
                        })}{' '}
                        <Link 
                          href="/msp/settings?tab=billing" 
                          className="text-primary-600 hover:text-primary-700 underline font-medium"
                        >
                          {t('clientTaxSettings.advanced.taxSourceOverride.notAvailable.link', {
                            defaultValue: 'billing settings'
                          })}
                        </Link>
                        {' '}
                        {t('clientTaxSettings.advanced.taxSourceOverride.notAvailable.messageEnd', {
                          defaultValue: 'to allow per-client tax source overrides.'
                        })}
                      </p>
                    </AlertDescription>
                  </Alert>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-between">
          <Button
            id="reset-tax-settings-button"
            type="button"
            onClick={() => {
              if (originalSettings) {
                setTaxSettings(JSON.parse(JSON.stringify(originalSettings)));
                setError(null);
              }
            }}
            variant="outline"
            disabled={isSubmitting}
          >
            {t('clientTaxSettings.advanced.actions.reset', { defaultValue: 'Reset Changes' })}
          </Button>
          <Button
            id="update-tax-settings-button"
            type="submit"
            variant="default"
            disabled={isSubmitting}
          >
            {isSubmitting
              ? t('clientTaxSettings.advanced.actions.updating', { defaultValue: 'Updating...' })
              : t('clientTaxSettings.advanced.actions.update', { defaultValue: 'Update Tax Settings' })}
          </Button>
        </div>
      </form>
    </div>
  );
};

export default TaxSettingsForm;
