import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { DollarSign, Package, Calendar, Info } from 'lucide-react';
import { AddModal, AddModalSection } from '../../ui/AddModal/AddModal';
import { ProductSelector } from './ProductSelector';
import {
  SupplierPriceListCreate,
  SupplierPriceListUpdate,
  SupplierPriceListResponse,
} from '../../../api/types/suppliers';
import { IngredientResponse, UnitOfMeasure } from '../../../api/types/inventory';

interface PriceListModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (priceListData: SupplierPriceListCreate | SupplierPriceListUpdate) => Promise<void>;
  mode: 'create' | 'edit';
  initialData?: SupplierPriceListResponse;
  loading?: boolean;
  excludeProductIds?: string[];
  // Wait-for-refetch support
  waitForRefetch?: boolean;
  isRefetching?: boolean;
  onSaveComplete?: () => Promise<void>;
}

export const PriceListModal: React.FC<PriceListModalProps> = ({
  isOpen,
  onClose,
  onSave,
  mode,
  initialData,
  loading = false,
  excludeProductIds = [],
  waitForRefetch,
  isRefetching,
  onSaveComplete,
}) => {
  const { t } = useTranslation(['suppliers', 'common']);
  const [selectedProduct, setSelectedProduct] = useState<IngredientResponse | undefined>();
  const [formData, setFormData] = useState<Record<string, any>>({});

  // Initialize form data when modal opens or initialData changes
  useEffect(() => {
    if (isOpen) {
      if (mode === 'edit' && initialData) {
        setFormData({
          inventory_product_id: initialData.inventory_product_id,
          product_code: initialData.product_code || '',
          unit_price: initialData.unit_price,
          unit_of_measure: initialData.unit_of_measure,
          minimum_order_quantity: initialData.minimum_order_quantity || '',
          price_per_unit: initialData.price_per_unit,
          effective_date: initialData.effective_date?.split('T')[0] || new Date().toISOString().split('T')[0],
          expiry_date: initialData.expiry_date?.split('T')[0] || '',
          is_active: initialData.is_active ? 'true' : 'false',
          brand: initialData.brand || '',
          packaging_size: initialData.packaging_size || '',
          origin_country: initialData.origin_country || '',
          shelf_life_days: initialData.shelf_life_days || '',
          storage_requirements: initialData.storage_requirements || '',
        });
      } else {
        // Reset form for create mode
        setFormData({
          inventory_product_id: '',
          product_code: '',
          unit_price: '',
          unit_of_measure: 'kg',
          minimum_order_quantity: '',
          price_per_unit: '',
          effective_date: new Date().toISOString().split('T')[0],
          expiry_date: '',
          is_active: 'true',
          brand: '',
          packaging_size: '',
          origin_country: '',
          shelf_life_days: '',
          storage_requirements: '',
        });
        setSelectedProduct(undefined);
      }
    }
  }, [isOpen, mode, initialData]);

  const handleProductChange = (productId: string, product?: IngredientResponse) => {
    setSelectedProduct(product);
    setFormData(prev => ({
      ...prev,
      inventory_product_id: productId,
      // Auto-fill some fields from product if available
      unit_of_measure: product?.unit_of_measure || prev.unit_of_measure,
      brand: product?.brand || prev.brand,
    }));
  };

  const handleFieldChange = (fieldName: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      [fieldName]: value,
    }));
  };

  const handleSave = async (data: Record<string, any>) => {
    // Clean and prepare the data
    const priceListData: SupplierPriceListCreate | SupplierPriceListUpdate = {
      inventory_product_id: data.inventory_product_id,
      product_code: data.product_code || null,
      unit_price: parseFloat(data.unit_price),
      unit_of_measure: data.unit_of_measure,
      minimum_order_quantity: data.minimum_order_quantity ? parseFloat(data.minimum_order_quantity) : null,
      price_per_unit: parseFloat(data.price_per_unit),
      effective_date: data.effective_date || undefined,
      expiry_date: data.expiry_date || null,
      is_active: data.is_active === 'true' || data.is_active === true,
      brand: data.brand || null,
      packaging_size: data.packaging_size || null,
      origin_country: data.origin_country || null,
      shelf_life_days: data.shelf_life_days ? parseInt(data.shelf_life_days) : null,
      storage_requirements: data.storage_requirements || null,
    };

    await onSave(priceListData);
  };

  const unitOptions = [
    { label: t('common:units.kg'), value: UnitOfMeasure.KILOGRAMS },
    { label: t('common:units.g'), value: UnitOfMeasure.GRAMS },
    { label: t('common:units.l'), value: UnitOfMeasure.LITERS },
    { label: t('common:units.ml'), value: UnitOfMeasure.MILLILITERS },
    { label: t('common:units.units'), value: UnitOfMeasure.UNITS },
    { label: t('common:units.pieces'), value: UnitOfMeasure.PIECES },
    { label: t('common:units.packages'), value: UnitOfMeasure.PACKAGES },
    { label: t('common:units.bags'), value: UnitOfMeasure.BAGS },
    { label: t('common:units.boxes'), value: UnitOfMeasure.BOXES },
  ];

  const sections: AddModalSection[] = [
    {
      title: t('price_list.sections.product_selection'),
      icon: Package,
      columns: 1,
      fields: [
        {
          name: 'inventory_product_id',
          label: t('price_list.fields.product'),
          type: 'component',
          required: true,
          component: ProductSelector,
          componentProps: {
            value: formData.inventory_product_id,
            onChange: handleProductChange,
            excludeIds: mode === 'create' ? excludeProductIds : [],
            disabled: mode === 'edit', // Can't change product in edit mode
            isRequired: true,
          },
          helpText: mode === 'edit'
            ? t('price_list.help.product_locked')
            : t('price_list.help.select_product'),
        },
        {
          name: 'product_code',
          label: t('price_list.fields.product_code'),
          type: 'text',
          required: false,
          placeholder: t('price_list.placeholders.product_code'),
          helpText: t('price_list.help.product_code'),
        },
      ],
    },
    {
      title: t('price_list.sections.pricing'),
      icon: DollarSign,
      columns: 2,
      fields: [
        {
          name: 'unit_price',
          label: t('price_list.fields.unit_price'),
          type: 'number',
          required: true,
          placeholder: '0.00',
          validation: (value) => {
            const num = parseFloat(value as string);
            if (isNaN(num) || num <= 0) {
              return t('price_list.validation.price_positive');
            }
            return null;
          },
          helpText: t('price_list.help.unit_price'),
        },
        {
          name: 'price_per_unit',
          label: t('price_list.fields.price_per_unit'),
          type: 'number',
          required: true,
          placeholder: '0.00',
          validation: (value) => {
            const num = parseFloat(value as string);
            if (isNaN(num) || num <= 0) {
              return t('price_list.validation.price_positive');
            }
            return null;
          },
          helpText: t('price_list.help.price_per_unit'),
        },
        {
          name: 'unit_of_measure',
          label: t('price_list.fields.unit_of_measure'),
          type: 'select',
          required: true,
          options: unitOptions,
          helpText: t('price_list.help.unit_of_measure'),
        },
        {
          name: 'minimum_order_quantity',
          label: t('price_list.fields.minimum_order'),
          type: 'number',
          required: false,
          placeholder: '0',
          helpText: t('price_list.help.minimum_order'),
        },
      ],
    },
    {
      title: t('price_list.sections.validity'),
      icon: Calendar,
      columns: 2,
      fields: [
        {
          name: 'effective_date',
          label: t('price_list.fields.effective_date'),
          type: 'date',
          required: false,
          defaultValue: new Date().toISOString().split('T')[0],
          helpText: t('price_list.help.effective_date'),
        },
        {
          name: 'expiry_date',
          label: t('price_list.fields.expiry_date'),
          type: 'date',
          required: false,
          helpText: t('price_list.help.expiry_date'),
        },
        {
          name: 'is_active',
          label: t('price_list.fields.is_active'),
          type: 'select',
          required: false,
          defaultValue: 'true',
          options: [
            { label: t('common:yes'), value: 'true' },
            { label: t('common:no'), value: 'false' }
          ],
          helpText: t('price_list.help.is_active'),
        },
      ],
    },
    {
      title: t('price_list.sections.product_details'),
      icon: Info,
      columns: 2,
      fields: [
        {
          name: 'brand',
          label: t('price_list.fields.brand'),
          type: 'text',
          required: false,
          placeholder: t('price_list.placeholders.brand'),
        },
        {
          name: 'packaging_size',
          label: t('price_list.fields.packaging_size'),
          type: 'text',
          required: false,
          placeholder: t('price_list.placeholders.packaging_size'),
          helpText: t('price_list.help.packaging_size'),
        },
        {
          name: 'origin_country',
          label: t('price_list.fields.origin_country'),
          type: 'text',
          required: false,
          placeholder: t('price_list.placeholders.origin_country'),
        },
        {
          name: 'shelf_life_days',
          label: t('price_list.fields.shelf_life_days'),
          type: 'number',
          required: false,
          placeholder: '0',
          helpText: t('price_list.help.shelf_life_days'),
        },
        {
          name: 'storage_requirements',
          label: t('price_list.fields.storage_requirements'),
          type: 'textarea',
          required: false,
          placeholder: t('price_list.placeholders.storage_requirements'),
          span: 2,
        },
      ],
    },
  ];

  return (
    <AddModal
      isOpen={isOpen}
      onClose={onClose}
      title={mode === 'create'
        ? t('price_list.modal.title_create')
        : t('price_list.modal.title_edit')
      }
      subtitle={mode === 'create'
        ? t('price_list.modal.subtitle_create')
        : t('price_list.modal.subtitle_edit')
      }
      sections={sections}
      onSave={handleSave}
      onCancel={onClose}
      size="xl"
      loading={loading || isRefetching}
      initialData={formData}
      onFieldChange={handleFieldChange}
      waitForRefetch={waitForRefetch}
      showSuccessState={true}
    />
  );
};
