import React, { useState, useContext } from 'react';
import './NewSuppliers.css';
import { langContext } from '../../context/LenguageContext';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

export default function NewSuppliers() {
  const { lang } = useContext(langContext);
  const [suppliers, setSuppliers] = useState([]);
  const [success, setSuccess] = useState(false);

  //Generador de IDs automáticos tipo SUP-0001
  const generateSupplierId = (index) => {
    const num = (index + 1).toString().padStart(4, '0');
    return `SUP-${num}`;
  };

  //Esquema Yup (solo RFC y Name son obligatorios)
  const supplierSchema = Yup.object({
    new_rfc_suppliers: Yup.string()
      .required(lang === 'en' ? 'RFC is required' : 'El RFC es obligatorio')
      .min(12, lang === 'en' ? 'Min 12 characters' : 'Mínimo 12 caracteres')
      .max(13, lang === 'en' ? 'Max 13 characters' : 'Máximo 13 caracteres'),

    new_name_suppliers: Yup.string()
      .required(lang === 'en' ? 'Name is required' : 'El nombre es obligatorio')
      .min(10, lang === 'en' ? 'Min 10 characters' : 'Mínimo 10 caracteres')
      .max(50, lang === 'en' ? 'Max 50 characters' : 'Máximo 50 caracteres'),

    new_email_suppliers: Yup.string()
      .email(lang === 'en' ? 'Invalid email format' : 'Formato de correo no válido')
      .nullable()
      .transform((value, originalValue) => originalValue.trim() === '' ? null : value),

    new_phone_suppliers: Yup.string()
      .max(15, lang === 'en' ? 'Max 15 digits' : 'Máximo 15 dígitos')
      .matches(/^[0-9+\- ]*$/, lang === 'en' ? 'Only numbers and symbols (+, -)' : 'Solo números y símbolos (+, -)')
      .nullable()
      .transform((value, originalValue) => originalValue.trim() === '' ? null : value)
  });

  //Inicializar react-hook-form con Yup
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting }
  } = useForm({
    resolver: yupResolver(supplierSchema),
    defaultValues: {
      new_rfc_suppliers: '',
      new_name_suppliers: '',
      new_email_suppliers: '',
      new_phone_suppliers: ''
    }
  });

  const [errorMsg, setErrorMsg] = useState('');

  const onSubmit = async (data) => {
    setSuccess(false);
    setErrorMsg('');

    const body = {
      new_name_supp: data.new_name_suppliers,
      new_rfc_supp: data.new_rfc_suppliers,
      new_mail_supp: data.new_email_suppliers,
      new_phone_supp: data.new_phone_suppliers
    };

    try {
      const response = await fetch(
        `${import.meta.env.VITE_API_BASE_URL}/products/newsupplier`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(body)
        }
      );

      const result = await response.json();

      //Si el backend indica conflicto o duplicado
      if (!response.ok) {
        if (response.status === 409 || result.message?.toLowerCase().includes('exists')) {
          setErrorMsg(
            lang === 'en'
              ? 'This supplier is already registered.'
              : 'Este proveedor ya está registrado.'
          );
        } else {
          setErrorMsg(
            lang === 'en'
              ? 'Error saving supplier.'
              : 'Error al guardar el proveedor.'
          );
        }
        return;
      }

      console.log('Supplier creado:', result);
      setSuppliers(prev => [...prev, result]);
      setSuccess(true);
      reset();

    } catch (error) {
      console.error('Error al crear supplier:', error);
      setErrorMsg(
        lang === 'en'
          ? 'Network error while saving supplier.'
          : 'Error de red al guardar el proveedor.'
      );
    }
  };

  // Actualizar estado de pago (PUT)
  const updatePaymentStatus = async (supplierId) => {
    try {
      const response = await fetch(
        `${import.meta.env.VITE_API_BASE_URL}/status/paymentupdate/${supplierId}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ status: 1 })
        }
      );

      if (!response.ok) throw new Error('Error al actualizar status');

      const result = await response.json();
      console.log('Payment status updated:', result);
    } catch (error) {
      console.error('Error actualizando el status de pago:', error);
    }
  };


  return (
    <div className="new-supplier-container">
      <div className="form-card">
        <h2>{lang === 'en' ? 'New Supplier' : 'Nuevo Proveedor'}</h2>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="form-grid">
            {/* RFC */}
            <div>
              <label>RFC*</label>
              <input type="text" {...register('new_rfc_suppliers')} />
              {errors.new_rfc_suppliers && (
                <p className="error-text">{errors.new_rfc_suppliers.message}</p>
              )}
            </div>

            {/* Name */}
            <div>
              <label>{lang === 'en' ? 'Name*' : 'Nombre*'}</label>
              <input type="text" {...register('new_name_suppliers')} />
              {errors.new_name_suppliers && (
                <p className="error-text">{errors.new_name_suppliers.message}</p>
              )}
            </div>

            {/* Email */}
            <div>
              <label>Email</label>
              <input type="email" {...register('new_email_suppliers')} />
              {errors.new_email_suppliers && (
                <p className="error-text">{errors.new_email_suppliers.message}</p>
              )}
            </div>

            {/* Phone */}
            <div>
              <label>{lang === 'en' ? 'Phone' : 'Teléfono'}</label>
              <input type="text" {...register('new_phone_suppliers')} />
              {errors.new_phone_suppliers && (
                <p className="error-text">{errors.new_phone_suppliers.message}</p>
              )}
            </div>
          </div>

          {errorMsg && (
            <p style={{ color: 'red', fontWeight: 'bold' }}>
              {errorMsg}
            </p>
          )}


          {success && (
            <p style={{ color: 'green', fontWeight: 'bold' }}>
              {lang === 'en'
                ? 'Supplier saved successfully!'
                : '¡Proveedor guardado exitosamente!'}
            </p>
          )}

          <div className="save-button-wrapper">
            <button type="submit" className="save-button" disabled={isSubmitting}>
              {isSubmitting
                ? (lang === 'en' ? 'Saving...' : 'Guardando...')
                : (lang === 'en' ? 'Save Supplier' : 'Guardar Proveedor')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
