"use client";

import { Card, Typography } from "antd";
import InputItem from "@/app/Components/FormItems";
import { handleChange, validateAndAlert } from "@/app/utils/form";
import Swal from "sweetalert2";

import {
  adminEmail,
  countries,
  errorMessage,
  formattedDateWithTime,
  mailResponse,
  successMessage,
} from "@/app/utils/variables";
import {
  GeneralMailTemplate,
  KycEmailTemplate,
  KycEmailTemplateToUser,
} from "../EmailTemplates/GeneralMailTemplate";
import { useState } from "react";
import { Loader } from "../Loader";
import { useSiteContext } from "@/app/Context/SiteContext";

const { Paragraph } = Typography;

export default function KycForm() {
  const [pendingUploads, setPendingUploads] = useState({});

  const entityOptions = [
    { label: "Proprietorship", value: "Proprietorship" },
    { label: "Partnership", value: "Partnership" },
    { label: "LLC", value: "LLC" },
    { label: "Other", value: "Other" },
  ];

  const { setUploadProgress } = useSiteContext();
  const [formSubmitting, setFormSubmitting] = useState(false);
  const [form, setForm] = useState({
    // Company Details
    legalName: "",
    tradeName: "",
    entityType: "",
    otherEntityType: "", // shown only if entityType is "Other"
    incorporationDate: "",
    incorporationCountry: "",
    regNumber: "",
    taxId: "",

    // Registered Office Address
    regAddress1: "",
    regAddress2: "",
    regCity: "",
    regState: "",
    regCountry: "",
    regPostal: "",

    // Billing Address
    billSameAsReg: false,
    billAddress1: "",
    billAddress2: "",
    billCity: "",
    billState: "",
    billCountry: "",
    billPostal: "",

    // Primary Contact
    primaryName: "",
    primaryDesignation: "",
    primaryPhone: "",
    primaryEmail: "",

    // Alternate Contact
    altName: "",
    altDesignation: "",
    altPhone: "",
    altEmail: "",

    // File Uploads
    docTradeLicense: null,
    docTaxCert: null,
    docSignatoryId: null,
    docPOA: null,

    // Declaration
    declarationConfirmed: false,
  });

  const getFormData = () => {
    return {
      legalName: form.legalName,
      tradeName: form.tradeName,
      entityType: form.entityType,
      otherEntityType: form.otherEntityType,
      incorporationDate: formattedDateWithTime(form.incorporationDate),
      incorporationCountry: form.incorporationCountry,
      regNumber: form.regNumber,
      taxId: form.taxId,

      regAddress1: form.regAddress1,
      regAddress2: form.regAddress2,
      regCity: form.regCity,
      regState: form.regState,
      regCountry: form.regCountry,
      regPostal: form.regPostal,

      billSameAsReg: form.billSameAsReg,
      billAddress1: form.billAddress1,
      billAddress2: form.billAddress2,
      billCity: form.billCity,
      billState: form.billState,
      billCountry: form.billCountry,
      billPostal: form.billPostal,

      primaryName: form.primaryName,
      primaryDesignation: form.primaryDesignation,
      primaryPhone: form.primaryPhone,
      primaryEmail: form.primaryEmail,

      altName: form.altName,
      altDesignation: form.altDesignation,
      altPhone: form.altPhone,
      altEmail: form.altEmail,

      docTradeLicense: form.docTradeLicense,
      docTaxCert: form.docTaxCert,
      docSignatoryId: form.docSignatoryId,
      docPOA: form.docPOA,

      declarationConfirmed: form.declarationConfirmed,

      created_at: new Date(),
      updated_at: new Date(),
    };
  };

  const handleSubmit = async () => {
    const formData = getFormData();

    if (!validateAndAlert(formData, requiredFields)) return;

    if (!form.declarationConfirmed) {
      errorMessage("Agree to the declaration");
      return;
    }

    setFormSubmitting(true);

    try {
      const res = await fetch("/api/kyc", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      const dbData = await res.json();
      if (!res.ok) throw new Error(dbData.message || "Submission failed");

      const customerId = dbData.customerId;

      // 1. Send admin notification email first (if needed before DB insert)
      const mailRes = await mailResponse(
        adminEmail,
        `New KYC Submission – Customer ID: ${customerId}`,
        KycEmailTemplate(form, customerId)
      );

      const mailData = await mailRes.json();
      if (!mailRes.ok)
        throw new Error(mailData?.error || "Email to admin failed");

      const mailRestoUser = await mailResponse(
        form.primaryEmail,
        `KYC Submission Received – Customer ID: ${customerId}`,
        KycEmailTemplateToUser(customerId)
      );

      const mailUserData = await mailRestoUser.json();
      if (!mailRestoUser.ok)
        throw new Error(mailUserData?.error || "Email to user failed");

      // 4. Show success message
      Swal.fire({
        title: "KYC submitted successfully",
        icon: "success",
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        customClass: {
          popup: "custom-swal-popup",
          title: "custom-swal-title",
        },
      });

      setFormSubmitting(false);
      setForm([]);
    } catch (err) {
      setFormSubmitting(false);
      errorMessage(err.message || "Something went wrong");
    }
  };

  const requiredFields = [
    "legalName",
    "entityType",
    form.entityType === "Other" ? "otherEntityType" : null,
    "incorporationDate",
    "incorporationCountry",
    "regNumber",
    "taxId",
    "regAddress1",
    "regCity",
    "regState",
    "regCountry",
    // "regPostal",
    "primaryName",
    "primaryDesignation",
    "primaryPhone",
    "primaryEmail",
    "docTradeLicense",
    // "docTaxCert",
    //"docSignatoryId",
    // "docPOA",
    "declarationConfirmed",
  ].filter(Boolean);

  const handleFileUpload = (file, fieldName, displayName) => {
    const allowedTypes = [
      "application/pdf",
      "application/msword",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "application/vnd.ms-excel",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "image/jpeg",
      "image/png",
      "image/jpg",
      "image/webp",
    ];

    // ✅ Max size updated to 1 MB
    const maxSize = 1024 * 1024;

    if (!allowedTypes.includes(file.type)) {
      return errorMessage(
        "Unsupported file type. Allowed: PDF, Word, Excel, JPG, PNG, WebP."
      );
    }

    if (file.size > maxSize) {
      return errorMessage("File size should not exceed 1 MB.");
    }

    const formData = new FormData();
    const locationName = "doc/general";
    const storedFileName = `${Date.now()}-${file.name}`;

    formData.append("file", file);
    formData.append("locationName", locationName);
    formData.append("fileName", storedFileName);

    const xhr = new XMLHttpRequest();

    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        const percent = Math.round((event.loaded / event.total) * 100);
        setUploadProgress((prev) => ({
          ...prev,
          [fieldName]: percent,
        }));
      }
    };

    xhr.onload = () => {
      if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        if (response?.url) {
          const fileInfo = {
            url: response.url,
            fileName: displayName || file.name,
          };
          setPendingUploads((prev) => ({ ...prev, [fieldName]: fileInfo }));
          setForm((prev) => ({ ...prev, [fieldName]: fileInfo }));
          setUploadProgress((prev) => ({ ...prev, [fieldName]: null }));
        }
      } else {
        errorMessage("Upload failed");
        setUploadProgress((prev) => ({ ...prev, [fieldName]: null }));
      }
    };

    xhr.onerror = () => {
      errorMessage("Upload failed due to network error.");
      setUploadProgress((prev) => ({ ...prev, [fieldName]: null }));
    };

    xhr.open("POST", "/api/upload_doc");
    xhr.send(formData);
  };

  if (formSubmitting) {
    return <Loader full />;
  }

  return (
    <div className="sm:max-w-[700px] mx-auto grid gap-5 mt-5">
      {/* Intro */}
      <Card>
        <div className="grid gap-4">
          <h1 className="sm:text-2xl text-[5vw] font-bold">KYC FORM</h1>
          <p>
            Powered by <strong>Upturnist</strong>
          </p>
          <p className="text-gray-500">
            Thank you for partnering with Upturnist. As part of our onboarding
            process, please complete this Know Your Client (KYC) form to help us
            maintain accurate records and ensure smooth project coordination and
            billing.
          </p>
          <p className="text-gray-500">
            An authorized representative should fill out the form and attach the
            required documents. All information will be kept confidential and
            used only for internal and compliance purposes.
          </p>
        </div>
      </Card>

      {/* Company Details */}
      <Card title="Company Details">
        <div className="grid gap-4">
          <InputItem
            type="text"
            label="Legal Entity Name"
            name="legalName"
            value={form.legalName}
            onChange={(e) => handleChange(e, setForm)}
            required
          />
          <InputItem
            type="text"
            label="Trade Name (if different)"
            name="tradeName"
            value={form.tradeName}
            onChange={(e) => handleChange(e, setForm)}
          />

          {/* Type of Entity - Radio Group */}
          <div>
            <label className="font-medium block mb-3">Type of Entity</label>
            <div className="flex flex-wrap gap-4">
              {entityOptions.map((option) => (
                <label key={option.value} className="flex items-center gap-2">
                  <input
                    type="radio"
                    name="entityType"
                    value={option.value}
                    checked={form.entityType === option.value}
                    onChange={(e) => handleChange(e, setForm)}
                  />
                  {option.label}
                </label>
              ))}
            </div>
          </div>

          {form.entityType === "Other" && (
            <InputItem
              type="text"
              label="Please specify other entity type"
              name="otherEntityType"
              value={form.otherEntityType}
              onChange={(e) => handleChange(e, setForm)}
            />
          )}

          <InputItem
            type="date"
            label="Date of Incorporation"
            name="incorporationDate"
            value={form.incorporationDate}
            onChange={(e) => handleChange(e, setForm)}
          />
          <InputItem
            type="select"
            label="Country of Incorporation"
            name="incorporationCountry"
            value={form.incorporationCountry}
            onChange={(e) => handleChange(e, setForm)}
            options={countries || []}
          />
          <InputItem
            type="text"
            label="Company Registration / License Number"
            name="regNumber"
            value={form.regNumber}
            onChange={(e) => handleChange(e, setForm)}
          />
          <InputItem
            type="text"
            label="Tax Identification Number (TIN/VAT/TRN)"
            name="taxId"
            value={form.taxId}
            onChange={(e) => handleChange(e, setForm)}
          />
        </div>
      </Card>

      {/* Registered Office Address */}
      <Card title="Registered Office Address">
        <div className="grid gap-4">
          <InputItem
            type="textarea"
            label="Address"
            name="regAddress1"
            value={form.regAddress1}
            onChange={(e) => handleChange(e, setForm)}
          />

          <InputItem
            type="text"
            label="City"
            name="regCity"
            value={form.regCity}
            onChange={(e) => handleChange(e, setForm)}
          />
          <InputItem
            type="text"
            label="State/Province"
            name="regState"
            value={form.regState}
            onChange={(e) => handleChange(e, setForm)}
          />

          <InputItem
            type="select"
            label="Country"
            name="regCountry"
            value={form.regCountry}
            onChange={(e) => handleChange(e, setForm)}
            options={countries || []}
          />
          <InputItem
            type="text"
            label="Postal Code"
            name="regPostal"
            value={form.regPostal}
            onChange={(e) => handleChange(e, setForm)}
          />
        </div>
      </Card>

      {/* Billing Address */}
      <Card title="Communication / Billing Address">
        <div className="grid gap-4">
          <InputItem
            type="checkbox"
            label="Same in above office address"
            name="billSameAsReg"
            value={form.billSameAsReg}
            onChange={(e) => {
              const isChecked = e.target.checked;
              if (isChecked) {
                setForm((prev) => ({
                  ...prev,
                  billSameAsReg: true,
                  billAddress1: prev.regAddress1,
                  billAddress2: prev.regAddress2,
                  billCity: prev.regCity,
                  billState: prev.regState,
                  billCountry: prev.regCountry,
                  billPostal: prev.regPostal,
                }));
              } else {
                setForm((prev) => ({
                  ...prev,
                  billSameAsReg: false,
                  billAddress1: "",
                  billAddress2: "",
                  billCity: "",
                  billState: "",
                  billCountry: "",
                  billPostal: "",
                }));
              }
            }}
          />

          {!form.billSameAsReg && (
            <>
              <InputItem
                type="textarea"
                label="Address"
                name="billAddress1"
                value={form.billAddress1}
                onChange={(e) => handleChange(e, setForm)}
              />
              {/* <InputItem
                type="textarea"
                label="Address Line 2"
                name="billAddress2"
                value={form.billAddress2}
                onChange={(e) => handleChange(e, setForm)}
              /> */}
              <InputItem
                type="text"
                label="City"
                name="billCity"
                value={form.billCity}
                onChange={(e) => handleChange(e, setForm)}
              />
              <InputItem
                type="text"
                label="State/Province"
                name="billState"
                value={form.billState}
                onChange={(e) => handleChange(e, setForm)}
              />
              <InputItem
                type="text"
                label="Country"
                name="billCountry"
                value={form.billCountry}
                onChange={(e) => handleChange(e, setForm)}
              />
              <InputItem
                type="text"
                label="Postal Code"
                name="billPostal"
                value={form.billPostal}
                onChange={(e) => handleChange(e, setForm)}
              />
            </>
          )}
        </div>
      </Card>

      {/* Primary Contact */}
      <Card title="Primary Contact Person">
        <div className="grid gap-4">
          <InputItem
            type="text"
            label="Full Name"
            name="primaryName"
            value={form.primaryName}
            onChange={(e) => handleChange(e, setForm)}
          />
          <InputItem
            type="text"
            label="Designation"
            name="primaryDesignation"
            value={form.primaryDesignation}
            onChange={(e) => handleChange(e, setForm)}
          />

          <InputItem
            type="phone_with_code"
            defaultCountry="AE"
            label="Phone Number"
            name="primaryPhone"
            value={form.primaryPhone}
            onChange={(e) => handleChange(e, setForm)}
          />
          <InputItem
            type="email"
            label="Email Address"
            name="primaryEmail"
            value={form.primaryEmail}
            onChange={(e) => handleChange(e, setForm)}
          />
        </div>
      </Card>

      {/* Alternate Contact */}
      <Card title="Alternate Contact Person (Optional)">
        <div className="grid gap-4">
          <div>
            <InputItem
              type="text"
              label="Full Name"
              name="altName"
              value={form.altName}
              onChange={(e) => handleChange(e, setForm)}
            />
          </div>
          <div>
            <InputItem
              type="text"
              label="Designation"
              name="altDesignation"
              value={form.altDesignation}
              onChange={(e) => handleChange(e, setForm)}
            />
          </div>
          <div>
            <InputItem
              type="phone_with_code"
              defaultCountry="AE"
              label="Phone Number"
              name="altPhone"
              value={form.altPhone}
              onChange={(e) => handleChange(e, setForm)}
            />
          </div>
          <div>
            <InputItem
              type="email"
              label="Email Address"
              name="altEmail"
              value={form.altEmail}
              onChange={(e) => handleChange(e, setForm)}
            />
          </div>
        </div>
      </Card>

      {/* Documents Upload */}
      <Card title="Documents to be Attached">
        <div className="grid gap-4">
          <Paragraph>
            Please upload clear scanned copies of the following documents:
          </Paragraph>

          <div className="grid gap-5">
            <div className="mb-2">
              <InputItem
                type="drag_upload"
                hint="Company Registration / Trade License"
                name="docTradeLicense"
                value={form.docTradeLicense}
                onChange={(e) => handleChange(e, setForm)}
                handleFileUpload={(file, fieldName) =>
                  handleFileUpload(
                    file,
                    fieldName,
                    "Company Registration / Trade License"
                  )
                }
                maxFileSize={1024 * 1024}
                pendingUploads={pendingUploads}
              />
            </div>

            <div className="mb-2">
              <InputItem
                type="drag_upload"
                hint="Tax Registration Certificate (TRN/VAT/TIN)"
                name="docTaxCert"
                value={form.docTaxCert}
                onChange={(e) => handleChange(e, setForm)}
                handleFileUpload={(file, fieldName) =>
                  handleFileUpload(
                    file,
                    fieldName,
                    "Tax Registration Certificate (TRN/VAT/TIN)"
                  )
                }
                maxFileSize={1024 * 1024}
                pendingUploads={pendingUploads}
              />
            </div>
            <div className="mb-2">
              <InputItem
                type="drag_upload"
                hint="Authorized Signatory ID (Passport / National ID)"
                name="docSignatoryId"
                value={form.docSignatoryId}
                onChange={(e) => handleChange(e, setForm)}
                handleFileUpload={(file, fieldName) =>
                  handleFileUpload(
                    file,
                    fieldName,
                    "Authorized Signatory ID (Passport / National ID)"
                  )
                }
                maxFileSize={1024 * 1024}
                pendingUploads={pendingUploads}
              />
            </div>
            <div className="mb-2">
              <InputItem
                type="drag_upload"
                hint="Power of Attorney / Authorization Letter (if applicable)"
                name="docPOA"
                value={form.docPOA}
                onChange={(e) => handleChange(e, setForm)}
                handleFileUpload={(file, fieldName) =>
                  handleFileUpload(
                    file,
                    fieldName,
                    "Power of Attorney / Authorization Letter"
                  )
                }
                maxFileSize={1024 * 1024}
                pendingUploads={pendingUploads}
              />
            </div>
          </div>
        </div>
      </Card>

      {/* Declaration */}
      <Card title="Declaration">
        <div className="grid gap-4">
          <p className="text-gray-500">
            I/We hereby declare that the information provided is true, correct,
            and complete. I/We understand that this information is required for
            compliance purposes and authorize <strong>Upturnist</strong> to
            validate the details provided.
          </p>
          <InputItem
            type="checkbox"
            label="I agree to the above declaration"
            name="declarationConfirmed"
            value={form.declarationConfirmed}
            onChange={(e) => handleChange(e, setForm)}
          />
          <div className="mt-1">
            <InputItem
              type="button"
              name="Send"
              title="Confirm to Send"
              placeholder="Confirm to Send"
              onClick={handleSubmit}
              btnColor="primary"
              btnvariant="solid"
            />
          </div>
        </div>
      </Card>
    </div>
  );
}
