/**
 * AddOnEditorModal Component
 *
 * Modal for creating or editing add-on products with feature selection.
 */

import React, { useState, useEffect } from 'react';
import { Loader2 } from 'lucide-react';
import { Modal, FormInput, Alert } from '../../components/ui';
import { FeaturePicker } from './FeaturePicker';
import {
  useFeatures,
  useCreateAddOnProduct,
  useUpdateAddOnProduct,
  type AddOnProduct,
  type AddOnFeatureWrite,
} from '../../hooks/useBillingAdmin';

// =============================================================================
// Types
// =============================================================================

export interface AddOnEditorModalProps {
  isOpen: boolean;
  onClose: () => void;
  addon?: AddOnProduct | null;
}

interface FormData {
  code: string;
  name: string;
  description: string;
  price_monthly_cents: number;
  price_one_time_cents: number;
  stripe_product_id: string;
  stripe_price_id: string;
  is_stackable: boolean;
  is_active: boolean;
  selectedFeatures: AddOnFeatureWrite[];
}

// =============================================================================
// Component
// =============================================================================

export const AddOnEditorModal: React.FC<AddOnEditorModalProps> = ({
  isOpen,
  onClose,
  addon,
}) => {
  const isEditMode = !!addon;

  const [formData, setFormData] = useState<FormData>({
    code: '',
    name: '',
    description: '',
    price_monthly_cents: 0,
    price_one_time_cents: 0,
    stripe_product_id: '',
    stripe_price_id: '',
    is_stackable: false,
    is_active: true,
    selectedFeatures: [],
  });

  const [errors, setErrors] = useState<Partial<Record<keyof FormData, string>>>({});

  // Fetch features
  const { data: features, isLoading: featuresLoading } = useFeatures();

  const createMutation = useCreateAddOnProduct();
  const updateMutation = useUpdateAddOnProduct();

  // Initialize form when addon changes
  useEffect(() => {
    if (addon) {
      setFormData({
        code: addon.code,
        name: addon.name,
        description: addon.description || '',
        price_monthly_cents: addon.price_monthly_cents,
        price_one_time_cents: addon.price_one_time_cents,
        stripe_product_id: addon.stripe_product_id || '',
        stripe_price_id: addon.stripe_price_id || '',
        is_stackable: addon.is_stackable,
        is_active: addon.is_active,
        selectedFeatures:
          addon.features?.map((af) => ({
            feature_code: af.feature.code,
            bool_value: af.bool_value,
            int_value: af.int_value,
          })) || [],
      });
    } else {
      setFormData({
        code: '',
        name: '',
        description: '',
        price_monthly_cents: 0,
        price_one_time_cents: 0,
        stripe_product_id: '',
        stripe_price_id: '',
        is_stackable: false,
        is_active: true,
        selectedFeatures: [],
      });
    }
    setErrors({});
  }, [addon, isOpen]);

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

    if (!formData.code.trim()) {
      newErrors.code = 'Code is required';
    } else if (!/^[a-z0-9_]+$/.test(formData.code)) {
      newErrors.code = 'Code must be lowercase letters, numbers, and underscores only';
    }

    if (!formData.name.trim()) {
      newErrors.name = 'Name is required';
    }

    if (formData.price_monthly_cents < 0) {
      newErrors.price_monthly_cents = 'Price cannot be negative';
    }

    if (formData.price_one_time_cents < 0) {
      newErrors.price_one_time_cents = 'Price cannot be negative';
    }

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

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

    const payload = {
      code: formData.code,
      name: formData.name,
      description: formData.description,
      price_monthly_cents: formData.price_monthly_cents,
      price_one_time_cents: formData.price_one_time_cents,
      stripe_product_id: formData.stripe_product_id,
      stripe_price_id: formData.stripe_price_id,
      is_stackable: formData.is_stackable,
      is_active: formData.is_active,
      features: formData.selectedFeatures,
    };

    try {
      if (isEditMode && addon) {
        await updateMutation.mutateAsync({
          id: addon.id,
          ...payload,
        });
      } else {
        await createMutation.mutateAsync(payload);
      }
      onClose();
    } catch (error) {
      console.error('Failed to save add-on:', error);
    }
  };

  const handleChange = (field: keyof FormData, value: string | number | boolean) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: undefined }));
    }
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={isEditMode ? `Edit ${addon?.name}` : 'Create Add-On'}
      size="4xl"
    >
      <div className="space-y-6">
        {/* Basic Info */}
        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 dark:text-white">Basic Information</h4>

          <div className="grid grid-cols-2 gap-4">
            <FormInput
              label="Code"
              value={formData.code}
              onChange={(e) => handleChange('code', e.target.value)}
              error={errors.code}
              placeholder="sms_credits_pack"
              disabled={isEditMode}
              hint={isEditMode ? 'Code cannot be changed' : 'Unique identifier (lowercase, underscores)'}
            />
            <FormInput
              label="Name"
              value={formData.name}
              onChange={(e) => handleChange('name', e.target.value)}
              error={errors.name}
              placeholder="SMS Credits Pack"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Description
            </label>
            <textarea
              value={formData.description}
              onChange={(e) => handleChange('description', e.target.value)}
              placeholder="Description of the add-on..."
              rows={2}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
            />
          </div>

          <div className="flex items-center gap-6">
            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="is_active"
                checked={formData.is_active}
                onChange={(e) => handleChange('is_active', e.target.checked)}
                className="rounded border-gray-300 dark:border-gray-600"
              />
              <label htmlFor="is_active" className="text-sm text-gray-700 dark:text-gray-300">
                Active (available for purchase)
              </label>
            </div>

            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="is_stackable"
                checked={formData.is_stackable}
                onChange={(e) => handleChange('is_stackable', e.target.checked)}
                className="rounded border-gray-300 dark:border-gray-600"
              />
              <label htmlFor="is_stackable" className="text-sm text-gray-700 dark:text-gray-300">
                Stackable (can purchase multiple, values compound)
              </label>
            </div>
          </div>
        </div>

        {/* Pricing */}
        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 dark:text-white">Pricing</h4>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Monthly Price
              </label>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
                <input
                  type="number"
                  min="0"
                  step="0.01"
                  value={(formData.price_monthly_cents / 100).toFixed(2)}
                  onChange={(e) =>
                    handleChange('price_monthly_cents', Math.round(parseFloat(e.target.value || '0') * 100))
                  }
                  className="w-full pl-7 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                />
              </div>
              {errors.price_monthly_cents && (
                <p className="mt-1 text-sm text-red-600">{errors.price_monthly_cents}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                One-Time Price
              </label>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
                <input
                  type="number"
                  min="0"
                  step="0.01"
                  value={(formData.price_one_time_cents / 100).toFixed(2)}
                  onChange={(e) =>
                    handleChange('price_one_time_cents', Math.round(parseFloat(e.target.value || '0') * 100))
                  }
                  className="w-full pl-7 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                />
              </div>
              {errors.price_one_time_cents && (
                <p className="mt-1 text-sm text-red-600">{errors.price_one_time_cents}</p>
              )}
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                For one-time purchases (credits, etc.)
              </p>
            </div>
          </div>
        </div>

        {/* Features */}
        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 dark:text-white">
            Features Granted by This Add-On
          </h4>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            Select the features that subscribers will receive when they purchase this add-on.
          </p>

          {featuresLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="w-6 h-6 animate-spin text-blue-600" />
            </div>
          ) : (
            <FeaturePicker
              features={features || []}
              selectedFeatures={formData.selectedFeatures}
              onChange={(selected) =>
                setFormData((prev) => ({ ...prev, selectedFeatures: selected }))
              }
            />
          )}
        </div>

        {/* Stripe Integration */}
        <div className="space-y-4">
          <h4 className="text-sm font-medium text-gray-900 dark:text-white">Stripe Integration</h4>

          <div className="grid grid-cols-2 gap-4">
            <FormInput
              label="Stripe Product ID"
              value={formData.stripe_product_id}
              onChange={(e) => handleChange('stripe_product_id', e.target.value)}
              placeholder="prod_..."
            />
            <FormInput
              label="Stripe Price ID"
              value={formData.stripe_price_id}
              onChange={(e) => handleChange('stripe_price_id', e.target.value)}
              placeholder="price_..."
            />
          </div>

          {!formData.stripe_product_id && (
            <Alert
              variant="info"
              message="Configure Stripe IDs to enable purchasing. Create the product in Stripe Dashboard first."
            />
          )}
        </div>
      </div>

      {/* Footer */}
      <div className="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
          type="button"
          onClick={onClose}
          className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
        >
          Cancel
        </button>
        <button
          type="button"
          onClick={handleSubmit}
          disabled={isPending}
          className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
        >
          {isPending && <Loader2 className="w-4 h-4 animate-spin" />}
          {isEditMode ? 'Save Changes' : 'Create Add-On'}
        </button>
      </div>
    </Modal>
  );
};
