import React from "react";
import validate from "validate.js";
import moment from "moment";
import { Text } from "react-native";

import CommonStyle from "../common/CommonStyle";
import { translate } from "../common/localize/i18n";

// Regex Pattern
const ifscPattern = /^[A-Za-z]{4}[a-zA-Z0-9]{7}$/;
const panNumberPattern = /[A-Z]{5}[0-9]{4}[A-Z]{1}/;
// const registrationNumberPattern = /(([A-Za-z]){2,3}(|-)(?:[0-9]){1,2}(|-)(?:[A-Za-z]){2}(|-)([0-9]){1,4})|(([A-Za-z]){2,3}(|-)([0-9]){1,4})/
const registrationNumberPattern = /^[A-Z]{2}[0-9]{1,2}[A-Z]{1,3}[0-9]{4}$/;
const RTOCodePattern = /^[A-Z]{2}[0-9]{2}$/;
const pincodeRegex = /^[1-9][0-9]{5}$/;
const contactNumberpattern = /^(\+\d{1,3}[- ]?)?\d{10}$/;
const GST = /\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}[Z]{1}[A-Z\d]{1}/;
const name = /^[a-zA-Z ]{2,30}$/;
const carChassisnumber = /[a-zA-Z0-9]{9}[a-zA-Z0-9-]{2}[0-9]{6}/;
const passportPattern = /^[A-Z]{1}[0-9]{7}$/;
const voterIdPattern = /^([a-zA-Z]){3}([0-9]){7}?$/;
const drivingLicensePattern =
  /^(([A-Z]{2}[0-9]{2})( ?)|([A-Z]{2}-[0-9]{2}))((19|20)[0-9][0-9])[0-9]{7}$/;

const noSpaceString = /^\S+$/;
const onlyCharNumber = /^[A-Za-z0-9_-]*$/;
const quoteNumberRegex = /^D{1}[0-9]{9}$/;

validate.extend(validate.validators.datetime, {
  parse: function (value, options) {
    return +moment.utc(value);
  },
  format: function (value, options) {
    var format = options.dateOnly ? "YYYY-MM-DD" : "YYYY-MM-DD hh:mm:ss";
    return moment.utc(value).format(format);
  },
});

validate.validators.array = (arrayItems, itemConstraints) => {
  const arrayItemErrors = arrayItems.reduce((errors, item, index) => {
    const error = validate(item, itemConstraints);
    if (error) errors[item.name] = error["value"][0];
    return errors;
  }, {});
  return Object.keys(arrayItemErrors).length > 0 ? arrayItemErrors : undefined;
};

const checkValuesOfArray = (item) => {
  return item.name !== null && item.value !== null;
};

const presence = {
  presence: {
    allowEmpty: false,
  },
};

const constraints = {
  // Input null / empty common validation
  checkInputValue: {
    label: { ...presence },
  },
  // Landing screen validation
  //registration number
  landingScreen1: {
    label: { ...presence, format: registrationNumberPattern },
  },
  //registration city
  landingScreen: {
    label: { ...presence },
  },
  // Online Payment validation
  OnlinePayment: {
    creditDebitNumber: {
      ...presence,
      numericality: true,
      length: { is: 16 },
    },
    chequeDate: { datetime: true },
    ifscCode: { format: ifscPattern },
    bankName: { ...presence },
    bankBranch: { ...presence },
  },
  RTOCode: {
    RTOCode: {
      format: RTOCodePattern,
    },
  },
  // Cheque Payment
  PaymentByCheque: {
    // panNumber: { format: panNumberPattern },
    panChequeNumber: { length: { is: 6 } },
    chequeDate: { datetime: true },
    // ifscCode: { format: ifscPattern },
    bankName: { ...presence },
    bankBranch: { ...presence },
  },
  // Generate Payment Link in Payment Screen validation
  GeneratePaymentLink: {
    paymentLinkPan: { format: panNumberPattern },
  },
  // Agent float payment in Payment screen Validation
  AgentFloatPayment: {
    amountToBeAdded: { ...presence },
    floatChequeNumber: { length: { is: 6 } },
    chequeDate: { datetime: true },
    ifscCode: { format: ifscPattern },
  },
  // Registration Year and Month
  yearMonthRegistration: {
    selectedYear: { ...presence },
    selectedMonth: { ...presence },
  },
  // Owner Details Screen Validation
  OwnerDetailsScreen: {
    ownername: { presence: true, format: name },
    ownerpincode: { format: pincodeRegex },
    owneremail: { email: true },
    ownermobile: { format: contactNumberpattern },
    owneraddress: { ...presence },
    // nomineename: { ...presence, format: name },
    // nomineerelation: { ...presence }
  },
  // Car Details
  CarDetails: {
    carchassisnumber: {
      ...presence,
      format: onlyCharNumber,
      length: { minimum: 6, maximum: 30 },
    },
    carenginenumber: {
      ...presence,
      format: onlyCharNumber,
      length: { minimum: 6, maximum: 20 },
    },
  },
  CarDetailsNew: {
    carchassisnumber: {
      ...presence,
      format: onlyCharNumber,
      length: { minimum: 17, maximum: 30 },
    },
    carenginenumber: {
      ...presence,
      format: onlyCharNumber,
      length: { minimum: 6, maximum: 20 },
    },
  },
  // Previous Policy Details Validation
  PreviousPolicydetails: {
    policyinsurer: { ...presence },
    policynumber: { ...presence },
    policyexpiry: { presence: true, datetime: true },
  },
  PreviousPolicydetailsTP: {
    policyinsurer: { ...presence },
    policynumber: { ...presence },
    policyexpiry: { presence: true, datetime: true },
    thirdPartyPolicyinsurer: { ...presence },
    thirdPartyPolicynumber: { ...presence },
    thirdPartyPolicyStart: { presence: true, datetime: true },
    thirdPartyPolicyExpiry: { presence: true, datetime: true },
  },
  PreviousPolicyThankYouDetails: {
    surwayConfirmPhone: { presence: true, format: contactNumberpattern },
    surwayConfirmEmail: { presence: true, email: true },
  },
  // Payment Screen thank you validation
  PaymentScreenThankYou: {
    surwayConfirmEmail: { email: true, presence: true },
    surwayConfirmPhone: { format: contactNumberpattern, presence: true },
  },
  // Agent Float Online payment validation
  AgentFloatPaymentOnline: {
    amountToBeAdded: { ...presence, numericality: true },
  },
  // Agent float Payment Validation
  AgentFloatPaymentCheque: {
    amountToBeAdded: { ...presence, numericality: true },
    floatChequeNumber: { length: { is: 6 } },
    chequeDate: { datetime: true },
    ifscCode: { format: ifscPattern },
  },
  chequeNumber: {
    chequeNumber: { length: { is: 6 } },
  },
  // NCB Modal Details Validation
  NCBModalDetails: {
    selectedPolicyType: { ...presence },
    eligibleNCBPercent: { ...presence },
    isClaimMadeLastYear: { ...presence },
  },
  NCBBikeModalDetails: {
    eligibleNCBPercent: { ...presence },
    isClaimMadeLastYear: { ...presence },
  },
  NCBDetails: {
    ncbEffectiveDate: { datetime: true },
    ncbIssuerName: { ...presence },
    ncbPreviousNumber: { ...presence },
    eligibleNCBPercent: { ...presence },
  },
  CommercialNCBDetails: {
    engineNumber: {
      ...presence,
      length: { minimum: 6, maximum: 20 },
      format: onlyCharNumber,
    },
    chassisNumber: {
      ...presence,
      length: { minimum: 6, maximum: 30 },
      format: onlyCharNumber,
    },
    ncbEffectiveDate: { datetime: true },
    ncbIssuerName: { ...presence },
    ncbPreviousNumber: { ...presence },
    eligibleNCBPercent: { ...presence },
  },
  CommercialNCB: {
    engineNumber: {
      ...presence,
      length: { minimum: 6, maximum: 20 },
      format: onlyCharNumber,
    },
    chassisNumber: {
      ...presence,
      length: { minimum: 6, maximum: 30 },
      format: onlyCharNumber,
    },
  },
  whatsappDetails: {
    mobileNumber: { format: contactNumberpattern },
  },
  emailDetails: {
    email: { presence: true, email: true },
  },
  bankName: {
    bankName: { presence: true, format: name },
  },
  pincode: {
    pincode: { presence: true, format: pincodeRegex },
  },
  panNumber: {
    panNumber: { presence: true, format: panNumberPattern },
  },
  passPort: {
    name: { presence: true, format: passportPattern },
  },
  voterId: {
    name: { presence: true, format: voterIdPattern },
  },
  drivingLicense: {
    name: { presence: true, format: drivingLicensePattern },
  },
  taxBenefit: {
    name: { ...presence },
    email: { email: true },
    mobilenumber: { format: contactNumberpattern },
    address: { ...presence },
  },
  personObject: {
    Fullname: { ...presence },
    gender: { ...presence },
    maritalStatus: { ...presence },
    personHeight: { ...presence },
    personInch: { ...presence },
    personWeight: { ...presence },
    personProfession: { ...presence },
    personDocumentType: { ...presence },
    personDocumentNumber: { ...presence },
  },
  personObjectWithoutDocs: {
    Fullname: { ...presence },
    gender: { ...presence },
    maritalStatus: { ...presence },
    personHeight: { ...presence },
    personInch: { ...presence },
    personWeight: { ...presence },
    personProfession: { ...presence },
  },
  gst: {
    gstNumber: { presence: true, format: GST },
  },
  pinCode: {
    pinCode: { format: pincodeRegex },
  },
  address: {
    address: { ...presence },
  },
  name: { name: { presence: true, format: name } },
  personObject: {
    Fullname: { ...presence },
    gender: { ...presence },
    maritalStatus: { ...presence },
    personHeight: { ...presence },
    personInch: { ...presence },
    personWeight: { ...presence },
    personProfession: { ...presence },
    personDocumentType: { ...presence },
    personDocumentNumber: { ...presence },
  },
  personObjectWithoutProposer: {
    Fullname: { ...presence },
    gender: { ...presence },
    personProfession: { ...presence },
    personDocumentType: { ...presence },
    personDocumentNumber: { ...presence },
  },
  personObjectWithoutDocs: {
    Fullname: { ...presence },
    gender: { ...presence },
    maritalStatus: { ...presence },
    personHeight: { ...presence },
    personInch: { ...presence },
    personWeight: { ...presence },
    personProfession: { ...presence },
  },
  gst: {
    gstNumber: { presence: true, format: GST },
  },
  pinCode: {
    pinCode: { format: pincodeRegex },
  },
  address: {
    address: { ...presence },
  },
  name: { name: { presence: true, format: name } },
  // Member Birthdays Details
  MemberBirthdayScreen: {
    birthdayDetails: {
      array: {
        name: { ...presence },
        value: { ...presence },
      },
    },
  },
  OTPDetails: {
    phoneNumber: { ...presence },
    currentOTP: { ...presence },
  },
  OTPPhoneNumber: {
    phoneNumber: { ...presence, length: { is: 10 }, numericality: true },
  },
  ifsc: {
    ifsc: { format: ifscPattern },
  },
  micr: {
    micr: { length: { is: 9 }, numericality: true },
  },
  ifscCode: { format: ifscPattern },
  micrCode: {
    micrCode: { length: { is: 9 }, numericality: true },
  },
  HealthCustomerDetails: {
    selfName: { ...presence, format: name },
    selfEmail: { presence: true, email: true },
    selfContact: { format: contactNumberpattern },
  },
  referenceCode: {
    referenceCode: { ...presence, format: onlyCharNumber },
  },
  quoteNumber: {
    quoteNumber: { ...presence, format: quoteNumberRegex },
  },
};

const renderErrorMsge = (props) => {
  let errorMsge = null;
  const { type, text, style } = props;
  switch (type) {
    case "select":
      errorMsge = `Select ${text}`;
      break;
    case "invalid":
      errorMsge = `Invalid ${text}`;
      break;
    case "input":
      errorMsge = `Enter ${text}`;
      break;
    case "none":
      errorMsge = text;
      break;
    case "one":
      errorMsge = "Select atleast one field";
      break;
    case "custom":
      errorMsge = text;
      break;
    default:
      errorMsge = "Fill all the details";
  }
  console.log("\x1B[31m", "ERROR ", errorMsge, "\x1B[39m");
  return (
    <Text style={[CommonStyle.errorText, style]}>{translate(errorMsge)}</Text>
  );
};

const Validation = (valueObj, type) => {
  return validate(valueObj, constraints[type]);
};

export { renderErrorMsge };

export default Validation;
