import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { SetupStepProps } from '../types';
import { useSuppliers, useCreateSupplier, useUpdateSupplier, useDeleteSupplier } from '../../../../api/hooks/suppliers';
import { SupplierType } from '../../../../api/types/suppliers';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useAuthUser } from '../../../../stores/auth.store';
import type { SupplierCreate, SupplierUpdate } from '../../../../api/types/suppliers';
import { SupplierProductManager } from './SupplierProductManager';
import { useAutoSaveDraft, useStepDraft, useDeleteStepDraft } from '../../../../api/hooks/onboarding';

const STEP_NAME = 'suppliers-setup';

export const SuppliersSetupStep: React.FC<SetupStepProps> = ({
  onNext,
  onPrevious,
  onComplete,
  onSkip,
  onUpdate,
  canContinue,
  isFirstStep,
  isLastStep
}) => {
  const { t } = useTranslation();

  // Get tenant ID
  const currentTenant = useCurrentTenant();
  const user = useAuthUser();
  const tenantId = currentTenant?.id || user?.tenant_id || '';

  // Fetch suppliers
  const { data: suppliersData, isLoading } = useSuppliers(tenantId);
  const suppliers = suppliersData || [];

  // Mutations
  const createSupplierMutation = useCreateSupplier();
  const updateSupplierMutation = useUpdateSupplier();
  const deleteSupplierMutation = useDeleteSupplier();

  // Draft auto-save hooks
  const { data: draftData, isLoading: isLoadingDraft } = useStepDraft(STEP_NAME);
  const { saveDraft, saveDraftImmediately, cancelPendingSave } = useAutoSaveDraft(STEP_NAME, 2000);
  const deleteStepDraft = useDeleteStepDraft();
  const draftRestoredRef = useRef(false);
  const stepCompletedRef = useRef(false); // Track if step has been completed to prevent draft saves after completion

  // Form state
  const [isAdding, setIsAdding] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    supplier_type: 'ingredients' as SupplierType,
    contact_person: '',
    phone: '',
    email: '',
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  // Restore draft data on mount (only once)
  useEffect(() => {
    if (!isLoadingDraft && draftData?.draft_data && !draftRestoredRef.current) {
      draftRestoredRef.current = true;
      const draft = draftData.draft_data;

      if (draft.formData) {
        setFormData(draft.formData);
      }
      if (draft.isAdding !== undefined) {
        setIsAdding(draft.isAdding);
      }
      if (draft.editingId !== undefined) {
        setEditingId(draft.editingId);
      }

      console.log('✅ Restored suppliers-setup draft:', draft);
    }
  }, [isLoadingDraft, draftData]);

  // Auto-save draft when form data changes (only when form is open)
  useEffect(() => {
    // CRITICAL: Do not save drafts after the step has been completed
    // This prevents overwriting completed status with draft data
    if (stepCompletedRef.current) {
      console.log('⏸️  Skipping draft save - step already completed');
      return;
    }

    // Only save after initial draft restoration
    if (!draftRestoredRef.current) return;
    // Only save if form is open
    if (!isAdding) return;

    const draftPayload = {
      formData,
      isAdding,
      editingId,
    };

    saveDraft(draftPayload);
  }, [formData, isAdding, editingId, saveDraft]);

  // Notify parent when count changes
  useEffect(() => {
    onUpdate?.({
      itemCount: suppliers.length,
      canContinue: suppliers.length >= 1,
    });
  }, [suppliers.length, onUpdate]);

  // Validation
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = t('setup_wizard:suppliers.errors.name_required', 'Name is required');
    }

    if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = t('setup_wizard:suppliers.errors.email_invalid', 'Invalid email format');
    }

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

  // Form handlers
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) return;

    try {
      if (editingId) {
        // Update existing supplier
        await updateSupplierMutation.mutateAsync({
          tenantId,
          supplierId: editingId,
          updateData: {
            name: formData.name,
            supplier_type: formData.supplier_type,
            contact_person: formData.contact_person || null,
            phone: formData.phone || null,
            email: formData.email || null,
          } as SupplierUpdate,
        });
        setEditingId(null);
      } else {
        // Create new supplier
        await createSupplierMutation.mutateAsync({
          tenantId,
          supplierData: {
            name: formData.name,
            supplier_type: formData.supplier_type,
            contact_person: formData.contact_person || undefined,
            phone: formData.phone || undefined,
            email: formData.email || undefined,
          } as SupplierCreate,
        });
      }

      // Reset form
      resetForm();
    } catch (error) {
      console.error('Error saving supplier:', error);
    }
  };

  const resetForm = (clearDraft: boolean = true) => {
    // Cancel any pending auto-save
    cancelPendingSave();

    setFormData({
      name: '',
      supplier_type: SupplierType.INGREDIENTS,
      contact_person: '',
      phone: '',
      email: '',
    });
    setErrors({});
    setIsAdding(false);
    setEditingId(null);

    // Delete draft if requested (after successful submission)
    if (clearDraft) {
      deleteStepDraft.mutate(STEP_NAME);
    }
  };

  const handleEdit = (supplier: any) => {
    setFormData({
      name: supplier.name,
      supplier_type: supplier.supplier_type,
      contact_person: supplier.contact_person || '',
      phone: supplier.phone || '',
      email: supplier.email || '',
    });
    setEditingId(supplier.id);
    setIsAdding(true);
  };

  const handleDelete = async (supplierId: string) => {
    if (!window.confirm(t('setup_wizard:suppliers.confirm_delete', 'Are you sure you want to delete this supplier?'))) {
      return;
    }

    try {
      await deleteSupplierMutation.mutateAsync({ tenantId, supplierId });
    } catch (error) {
      console.error('Error deleting supplier:', error);
    }
  };

  const supplierTypeOptions = [
    { value: 'ingredients', label: t('suppliers:type.ingredients', 'Ingredients') },
    { value: 'packaging', label: t('suppliers:type.packaging', 'Packaging') },
    { value: 'equipment', label: t('suppliers:type.equipment', 'Equipment') },
    { value: 'utilities', label: t('suppliers:type.utilities', 'Utilities') },
    { value: 'services', label: t('suppliers:type.services', 'Services') },
    { value: 'other', label: t('suppliers:type.other', 'Other') },
  ];

  return (
    <div className="space-y-6">
      {/* Why This Matters */}
      <div className="bg-[var(--color-info)]/10 border border-[var(--color-info)]/20 rounded-lg p-4">
        <h3 className="font-semibold text-[var(--text-primary)] mb-2 flex items-center gap-2">
          <svg className="w-5 h-5 text-[var(--color-info)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          {t('setup_wizard:why_this_matters', 'Why This Matters')}
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {t('setup_wizard:suppliers.why', 'Suppliers are the source of your ingredients. Setting them up now lets you track costs, manage orders, and analyze supplier performance.')}
        </p>
      </div>

      {/* Progress indicator */}
      <div className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] rounded-lg">
        <div className="flex items-center gap-2">
          <svg className="w-5 h-5 text-[var(--text-secondary)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
          </svg>
          <span className="text-sm font-medium text-[var(--text-primary)]">
            {t('setup_wizard:suppliers.added_count', { count: suppliers.length, defaultValue: '{count} supplier added' })}
          </span>
        </div>
        {suppliers.length >= 1 && (
          <div className="flex items-center gap-1 text-xs text-[var(--color-success)]">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
            {t('setup_wizard:suppliers.minimum_met', 'Minimum requirement met')}
          </div>
        )}
      </div>

      {/* Suppliers list */}
      {suppliers.length > 0 && (
        <div className="space-y-2">
          <h4 className="text-sm font-medium text-[var(--text-secondary)]">
            {t('setup_wizard:suppliers.your_suppliers', 'Your Suppliers')}
          </h4>
          <div className="space-y-2">
            {suppliers.map((supplier) => (
              <div
                key={supplier.id}
                className="p-3 bg-[var(--bg-secondary)] border border-[var(--border-secondary)] rounded-lg hover:border-[var(--border-primary)] transition-colors"
              >
                {/* Supplier Header */}
                <div className="flex items-center justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <h5 className="font-medium text-[var(--text-primary)] truncate">{supplier.name}</h5>
                      <span className="text-xs px-2 py-0.5 bg-[var(--bg-primary)] rounded-full text-[var(--text-secondary)]">
                        {supplierTypeOptions.find(opt => opt.value === supplier.supplier_type)?.label || supplier.supplier_type}
                      </span>
                    </div>
                    <div className="flex items-center gap-3 mt-1 text-xs text-[var(--text-secondary)]">
                      {supplier.contact_person && (
                        <span className="flex items-center gap-1">
                          <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                          </svg>
                          {supplier.contact_person}
                        </span>
                      )}
                      {supplier.phone && (
                        <span className="flex items-center gap-1">
                          <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                          </svg>
                          {supplier.phone}
                        </span>
                      )}
                      {supplier.email && (
                        <span className="flex items-center gap-1 truncate">
                          <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                          </svg>
                          {supplier.email}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2 ml-4">
                    <button
                      type="button"
                      onClick={() => handleEdit(supplier)}
                      className="p-1.5 text-[var(--text-secondary)] hover:text-[var(--color-primary)] hover:bg-[var(--bg-primary)] rounded transition-colors"
                      aria-label={t('common:edit', 'Edit')}
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                      </svg>
                    </button>
                    <button
                      type="button"
                      onClick={() => handleDelete(supplier.id)}
                      className="p-1.5 text-[var(--text-secondary)] hover:text-[var(--color-error)] hover:bg-[var(--color-error)]/10 rounded transition-colors"
                      aria-label={t('common:delete', 'Delete')}
                      disabled={deleteSupplierMutation.isPending}
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </div>

                {/* Product Management */}
                <SupplierProductManager
                  tenantId={tenantId}
                  supplierId={supplier.id}
                  supplierName={supplier.name}
                />
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Add/Edit form */}
      {isAdding ? (
        <form onSubmit={handleSubmit} className="space-y-4 p-4 border-2 border-[var(--color-primary)] rounded-lg bg-[var(--bg-secondary)]">
          <div className="flex items-center justify-between mb-2">
            <h4 className="font-medium text-[var(--text-primary)]">
              {editingId ? t('setup_wizard:suppliers.edit_supplier', 'Edit Supplier') : t('setup_wizard:suppliers.add_supplier', 'Add Supplier')}
            </h4>
            <button
              type="button"
              onClick={() => resetForm(false)}
              className="text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
            >
              {t('common:cancel', 'Cancel')}
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Name */}
            <div className="md:col-span-2">
              <label htmlFor="supplier-name" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:suppliers.fields.name', 'Supplier Name')} <span className="text-[var(--color-error)]">*</span>
              </label>
              <input
                id="supplier-name"
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className={`w-full px-3 py-2 bg-[var(--bg-primary)] border ${errors.name ? 'border-[var(--color-error)]' : 'border-[var(--border-secondary)]'} rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]`}
                placeholder={t('setup_wizard:suppliers.placeholders.name', 'e.g., Molinos SA, Distribuidora López')}
              />
              {errors.name && <p className="mt-1 text-xs text-[var(--color-error)]">{errors.name}</p>}
            </div>

            {/* Supplier Type */}
            <div>
              <label htmlFor="supplier-type" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:suppliers.fields.type', 'Type')} <span className="text-[var(--color-error)]">*</span>
              </label>
              <select
                id="supplier-type"
                value={formData.supplier_type}
                onChange={(e) => setFormData({ ...formData, supplier_type: e.target.value as SupplierType })}
                className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]"
              >
                {supplierTypeOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>

            {/* Contact Person */}
            <div>
              <label htmlFor="contact-person" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:suppliers.fields.contact_person', 'Contact Person')}
              </label>
              <input
                id="contact-person"
                type="text"
                value={formData.contact_person}
                onChange={(e) => setFormData({ ...formData, contact_person: e.target.value })}
                className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]"
                placeholder={t('setup_wizard:suppliers.placeholders.contact_person', 'e.g., Juan Pérez')}
              />
            </div>

            {/* Phone */}
            <div>
              <label htmlFor="phone" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:suppliers.fields.phone', 'Phone')}
              </label>
              <input
                id="phone"
                type="tel"
                value={formData.phone}
                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]"
                placeholder={t('setup_wizard:suppliers.placeholders.phone', 'e.g., +54 11 1234-5678')}
              />
            </div>

            {/* Email */}
            <div>
              <label htmlFor="email" className="block text-sm font-medium text-[var(--text-primary)] mb-1">
                {t('setup_wizard:suppliers.fields.email', 'Email')}
              </label>
              <input
                id="email"
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className={`w-full px-3 py-2 bg-[var(--bg-primary)] border ${errors.email ? 'border-[var(--color-error)]' : 'border-[var(--border-secondary)]'} rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-[var(--text-primary)]`}
                placeholder={t('setup_wizard:suppliers.placeholders.email', 'e.g., ventas@proveedor.com')}
              />
              {errors.email && <p className="mt-1 text-xs text-[var(--color-error)]">{errors.email}</p>}
            </div>
          </div>

          <div className="flex gap-2 pt-2">
            <button
              type="submit"
              disabled={createSupplierMutation.isPending || updateSupplierMutation.isPending}
              className="px-4 py-2 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary-dark)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
            >
              {(createSupplierMutation.isPending || updateSupplierMutation.isPending) ? (
                <span className="flex items-center gap-2">
                  <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  {t('common:saving', 'Saving...')}
                </span>
              ) : editingId ? (
                t('common:update', 'Update')
              ) : (
                t('common:add', 'Add')
              )}
            </button>
            <button
              type="button"
              onClick={() => resetForm(false)}
              className="px-4 py-2 text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-primary)] rounded-lg transition-colors"
            >
              {t('common:cancel', 'Cancel')}
            </button>
          </div>
        </form>
      ) : (
        <button
          type="button"
          onClick={() => setIsAdding(true)}
          className="w-full p-4 border-2 border-dashed border-[var(--border-secondary)] rounded-lg hover:border-[var(--color-primary)] hover:bg-[var(--bg-secondary)] transition-colors group"
        >
          <div className="flex items-center justify-center gap-2 text-[var(--text-secondary)] group-hover:text-[var(--color-primary)]">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            <span className="font-medium">
              {suppliers.length === 0
                ? t('setup_wizard:suppliers.add_first', 'Add Your First Supplier')
                : t('setup_wizard:suppliers.add_another', 'Add Another Supplier')}
            </span>
          </div>
        </button>
      )}

      {/* Loading state */}
      {isLoading && suppliers.length === 0 && (
        <div className="text-center py-8">
          <svg className="animate-spin h-8 w-8 text-[var(--color-primary)] mx-auto" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
          </svg>
          <p className="mt-2 text-sm text-[var(--text-secondary)]">
            {t('common:loading', 'Loading...')}
          </p>
        </div>
      )}

      {/* Navigation buttons */}
      <div className="flex items-center justify-between gap-4 pt-6 mt-6 border-t border-[var(--border-secondary)]">
        <div className="flex gap-2">
          {onPrevious && (
            <button
              type="button"
              onClick={onPrevious}
              className="px-4 py-2 text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)] rounded-lg transition-colors font-medium"
            >
              ← {t('common:previous', 'Anterior')}
            </button>
          )}
          {onSkip && suppliers.length === 0 && (
            <button
              type="button"
              onClick={onSkip}
              className="px-4 py-2 text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)] rounded-lg transition-colors"
            >
              {t('common:skip', 'Skip for now')}
            </button>
          )}
        </div>

        <div className="flex items-center gap-3">
          {!canContinue && suppliers.length === 0 && (
            <p className="text-sm text-[var(--color-warning)]">
              {t('setup_wizard:suppliers.add_minimum', 'Agrega al menos 1 proveedor para continuar')}
            </p>
          )}
          <button
            type="button"
            onClick={() => {
              // CRITICAL: Mark step as completed BEFORE calling onComplete
              // This prevents any pending auto-save from overwriting the completion
              stepCompletedRef.current = true;
              cancelPendingSave();
              onComplete?.();
            }}
            disabled={!canContinue}
            className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary-dark)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium flex items-center gap-2"
          >
            {t('common:next', 'Continuar →')}
          </button>
        </div>
      </div>
    </div>
  );
};
