/**
 * TenantEdit Component
 *
 * Modal form for creating tenants. Tenants are immutable after creation.
 *
 * @component
 * @layer Presentation
 */

import { useState } from 'react';
import { Building2, Globe, AlertCircle } from 'lucide-react';
import { Modal } from '@/components/shared';
import { Tenant, TenantStatus } from '@/domain/entities/Tenant';
import { useCreateTenant } from './hooks';
import { domainSchema } from '@archer/api-interface/schemas/customer-api/request';
import { useTranslation } from '@/i18n/TranslationProvider';

interface TenantFormData {
  name: string;
  domain: string;
}

/** Result returned when a new tenant is created */
export interface TenantCreateResult {
  tenant: Tenant;
  productionKey?: string;
}

interface TenantEditProps {
  /** Always null — create mode only */
  tenant: null;
  onSave: (result?: TenantCreateResult) => void;
  onCancel: () => void;
}

function isValidDomain(domain: string): boolean {
  return domainSchema.safeParse(domain).success;
}

export function TenantEdit({ onSave, onCancel }: TenantEditProps) {
  const { t } = useTranslation();
  const { mutate: createTenant, isPending: isCreating } = useCreateTenant();

  const wpDomain = import.meta.env.VITE_WP_EMBED === 'true'
    ? (window as any).archerAi?.domain || ''
    : '';

  const [formData, setFormData] = useState<TenantFormData>({
    name: wpDomain || '',
    domain: wpDomain,
  });

  const [errors, setErrors] = useState<Partial<Record<keyof TenantFormData, string>>>({});
  const [apiError, setApiError] = useState<string | null>(null);

  const validate = (): boolean => {
    const newErrors: Partial<Record<keyof TenantFormData, string>> = {};

    if (!formData.name.trim()) {
      newErrors.name = t('tenants.edit.nameRequired');
    }

    if (!formData.domain.trim()) {
      newErrors.domain = t('tenants.edit.domainRequired');
    } else if (!isValidDomain(formData.domain)) {
      newErrors.domain = t('tenants.edit.invalidDomain');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleChange = (field: keyof TenantFormData, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (apiError) setApiError(null);
    if (errors[field]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  const handleSave = async () => {
    if (!validate()) return;

    createTenant(
      {
        name: formData.name,
        domain: formData.domain,
        status: TenantStatus.ACTIVE,
      },
      {
        onSuccess: (result) => {
          onSave({ tenant: result.tenant, productionKey: result.productionKey });
        },
        onError: (error: any) => {
          const msg = error?.response?.data?.message || error?.message || 'Failed to create tenant';
          setApiError(msg);
        },
      }
    );
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !isCreating) {
      handleSave();
    } else if (e.key === 'Escape') {
      onCancel();
    }
  };

  return (
    <Modal
      title={t('tenants.edit.createTitle')}
      subtitle={t('tenants.edit.createSubtitle')}
      icon={<Building2 className="w-5 h-5 text-white" />}
      onClose={onCancel}
      footer={
        <>
          <button
            onClick={onCancel}
            className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            disabled={isCreating}
          >
            {t('common.cancel')}
          </button>
          <button
            onClick={handleSave}
            className="px-4 py-2 text-sm font-medium text-white bg-cyan-600 hover:bg-cyan-700 rounded-lg transition-all shadow-md hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"
            disabled={isCreating}
          >
            {isCreating ? t('common.saving') : t('tenants.edit.createTenant')}
          </button>
        </>
      }
    >
      <div className="space-y-6" onKeyDown={handleKeyPress}>
          {/* Name Field */}
          <div>
            <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
              {t('tenants.edit.tenantName')} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              id="name"
              value={formData.name}
              onChange={(e) => handleChange('name', e.target.value)}
              className={`w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 transition-colors ${
                errors.name
                  ? 'border-red-300 focus:ring-red-500'
                  : 'border-gray-300 focus:ring-primary-500'
              }`}
              placeholder={t('tenants.edit.namePlaceholder')}
              disabled={isCreating}
              autoFocus
            />
            {errors.name && (
              <p className="mt-1 text-sm text-red-600 flex items-center gap-1">
                <AlertCircle size={14} />
                {errors.name}
              </p>
            )}
          </div>

          {/* Domain Field */}
          <div>
            <label htmlFor="domain" className="block text-sm font-medium text-gray-700 mb-2">
              {t('common.domain')} <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <Globe className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
              <input
                type="text"
                id="domain"
                value={formData.domain}
                onChange={(e) => handleChange('domain', e.target.value.toLowerCase())}
                className={`w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 transition-colors ${
                  errors.domain
                    ? 'border-red-300 focus:ring-red-500'
                    : 'border-gray-300 focus:ring-primary-500'
                }`}
                placeholder={t('tenants.edit.domainPlaceholder')}
                disabled={isCreating}
              />
            </div>
            {errors.domain && (
              <p className="mt-1 text-sm text-red-600 flex items-center gap-1">
                <AlertCircle size={14} />
                {errors.domain}
              </p>
            )}
          </div>

          {/* API Error */}
          {apiError && (
            <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
              <AlertCircle size={16} className="shrink-0" />
              {apiError}
            </div>
          )}

        </div>
    </Modal>
  );
}
