"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Badge } from "@/src/components/ui/badge";
import { Button } from "@/src/components/ui/button";
import { Card, CardContent } from "@/src/components/ui/card";
import { Input } from "@/src/components/ui/input";
import { Label } from "@/src/components/ui/label";
import { Textarea } from "@/src/components/ui/textarea";
import {
  Globe,
  TrendingUp,
  Award,
  Users,
  CheckCircle2,
  FileCheck,
  Send,
} from "lucide-react";
import type { Metadata } from "next";
import axios from "axios";
import { toast } from "react-toastify";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

export const metadata: Metadata = {
  title: "For Manufacturers - Partner With Us | Export Your Products Globally",
  description:
    "Join Xpecto Global as a manufacturing partner. Access global markets in USA, Europe & Middle East. We help Indian manufacturers expand internationally with export support.",
  keywords: [
    "manufacturing partner India",
    "export partnership",
    "Indian manufacturers",
    "global market access",
    "supplier partnership",
    "export from India",
    "B2B manufacturing",
  ],
  alternates: {
    canonical: "/for-manufacturers",
  },
  openGraph: {
    title: "For Manufacturers - Partner With Xpecto Global",
    description:
      "Join us as a manufacturing partner. Access global markets and expand your business internationally.",
    type: "website",
  },
};

export default function ForManufacturers() {
  const [formState, setFormState] = useState({
    companyName: "",
    contactPerson: "",
    email: "",
    phone: "",
    location: "",
    productCategory: "",
    products: "",
    gst: "",
    iec: "",
    certifications: "",
    productionCapacity: "",
    message: "",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);

  // CAPTCHA states
  const [numberCaptcha, setNumberCaptcha] = useState({
    num1: 0,
    num2: 0,
    answer: "",
  });
  const [numberCaptchaValid, setNumberCaptchaValid] = useState(false);

  // Product categories array
  const productCategories = [
    "Agricultural Products",
    "Textiles & Garments",
    "Leather Products",
    "Chemicals",
    "Pharmaceuticals",
    "Engineering Goods",
    "Electronics",
    "Plastic & Rubber Products",
    "Food Processing",
    "Handicrafts",
    "Furniture",
    "Automobile Components",
    "Iron & Steel",
    "Paper Products",
    "Other",
  ];

  // Generate random numbers for CAPTCHA
  const generateNumberCaptcha = () => {
    const num1 = Math.floor(Math.random() * 10) + 1;
    const num2 = Math.floor(Math.random() * 10) + 1;
    setNumberCaptcha({ num1, num2, answer: "" });
    setNumberCaptchaValid(false);
  };

  useEffect(() => {
    generateNumberCaptcha();
  }, []);

  // Validate number CAPTCHA
  const validateNumberCaptcha = (value: string): boolean => {
    const expected = numberCaptcha.num1 + numberCaptcha.num2;
    const isValid = parseInt(value) === expected;
    setNumberCaptchaValid(isValid);
    return isValid;
  };

  // Validation functions
  const validateEmail = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const validatePhone = (phone: string): boolean => {
    if (!phone) return false; // Phone is required for manufacturers
    const phoneRegex = /^[0-9+\-\s()]{5,20}$/;
    return phoneRegex.test(phone);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validation - all fields are required for manufacturers
    if (!formState.companyName.trim()) {
      toast.error("Please enter your company name");
      return;
    }

    if (!formState.contactPerson.trim()) {
      toast.error("Please enter contact person name");
      return;
    }

    if (!formState.email.trim()) {
      toast.error("Please enter your email");
      return;
    }

    if (!validateEmail(formState.email)) {
      toast.error("Invalid email format");
      return;
    }

    if (!formState.phone.trim()) {
      toast.error("Please enter your phone number");
      return;
    }

    if (!validatePhone(formState.phone)) {
      toast.error("Please enter a valid phone number");
      return;
    }

    if (!formState.location.trim()) {
      toast.error("Please enter your location");
      return;
    }

    if (!formState.productCategory) {
      toast.error("Please select a product category");
      return;
    }

    if (!formState.products.trim()) {
      toast.error("Please list the products you manufacture");
      return;
    }

    if (!formState.gst.trim()) {
      toast.error("Please enter your GST number");
      return;
    }

    if (!formState.iec.trim()) {
      toast.error("Please enter your IEC number");
      return;
    }

    if (!formState.certifications.trim()) {
      toast.error("Please enter your certifications");
      return;
    }

    if (!formState.productionCapacity.trim()) {
      toast.error("Please enter your monthly production capacity");
      return;
    }

    if (!formState.message.trim()) {
      toast.error("Please enter additional information");
      return;
    }

    if (!numberCaptchaValid) {
      toast.error("Please solve the math problem correctly");
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await axios.post(`${BASE_URL}/api/for-manufacturers`, {
        companyName: formState.companyName,
        contactPerson: formState.contactPerson,
        email: formState.email,
        phone: formState.phone,
        location: formState.location,
        productCategory: formState.productCategory,
        products: formState.products,
        gst: formState.gst,
        iec: formState.iec,
        certifications: formState.certifications,
        productionCapacity: formState.productionCapacity,
        message: formState.message,
      });

      if (response?.data?.success) {
        toast.success(
          response?.data?.message || "Application submitted successfully!",
        );
        setIsSubmitted(true);

        // Reset form
        setFormState({
          companyName: "",
          contactPerson: "",
          email: "",
          phone: "",
          location: "",
          productCategory: "",
          products: "",
          gst: "",
          iec: "",
          certifications: "",
          productionCapacity: "",
          message: "",
        });

        generateNumberCaptcha(); // Generate new CAPTCHA after successful submission
      }
    } catch (error) {
      console.error("Error submitting form:", error);

      if (axios.isAxiosError(error)) {
        toast.error(
          error.response?.data?.message ||
            "Something went wrong. Please try again.",
        );
      } else {
        toast.error("An unexpected error occurred.");
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >,
  ) => {
    const { name, value } = e.target;

    // Phone number validation - only numbers, +, -, spaces, and parentheses allowed
    if (name === "phone") {
      const phoneRegex = /^[0-9+\-\s()]*$/;
      if (value === "" || phoneRegex.test(value)) {
        setFormState((prev) => ({
          ...prev,
          [name]: value,
        }));
      }
    } else {
      setFormState((prev) => ({
        ...prev,
        [name]: value,
      }));
    }
  };

  const benefits = [
    {
      icon: Globe,
      title: "Global Market Access",
      description:
        "Expand your reach to USA, Europe, Middle East, and Asia through our established trade networks",
    },
    {
      icon: TrendingUp,
      title: "Business Growth",
      description:
        "Scale your operations with consistent bulk orders from international buyers",
    },
    {
      icon: Award,
      title: "Quality Recognition",
      description:
        "Showcase your certifications and quality standards to premium global markets",
    },
    {
      icon: Users,
      title: "Partnership Support",
      description:
        "End-to-end support including documentation, logistics, and compliance guidance",
    },
  ];

  const requirements = [
    "Valid Business Registration",
    "GST Registration",
    "IEC (Import Export Code) - if applicable",
    "Quality Certifications (ISO, GMP, etc.)",
    "Production Capacity Details",
    "Product Testing Reports",
    "Factory/Facility Photos",
    "Sample Products",
  ];

  const onboardingSteps = [
    {
      step: "01",
      title: "Submit Application",
      description: "Fill out our partnership application form",
    },
    {
      step: "02",
      title: "Document Verification",
      description: "Submit required business and compliance documents",
    },
    {
      step: "03",
      title: "Quality Assessment",
      description: "Product samples and quality evaluation",
    },
    {
      step: "04",
      title: "Agreement",
      description: "Sign partnership agreement and terms",
    },
    {
      step: "05",
      title: "Onboarding",
      description: "Setup in our supplier network and start receiving orders",
    },
  ];

  return (
    <div className="bg-[#ffffff]">
      <section className="relative h-125 md:h-100 flex items-center bg-[#0B1C2D]">
        <div className="absolute inset-0 bg-linear-to-r from-[#0B1C2D] to-[#1a3a52] pointer-events-none"></div>
        <div className="relative z-10 max-w-360 mx-auto px-6 w-full">
          <Badge className="mb-4 bg-[#ffffff]/10 text-[#ffffff] hover:bg-[#ffffff]/20">
            For Manufacturers
          </Badge>
          <h1 className="text-4xl md:text-5xl font-bold text-[#ffffff] mb-6">
            {"Partner With Us – Expand Globally"}
          </h1>
          <p className="text-xl text-gray-300 max-w-3xl">
            Join Xpecto Global as a verified manufacturer and expand your
            products to international markets
          </p>
        </div>
      </section>

      <section className="py-20">
        <div className="max-w-360 mx-auto px-6">
          <div className="max-w-4xl mx-auto text-center mb-16">
            <h2 className="text-3xl font-bold text-[#0B1C2D] mb-6">
              Why Partner With Xpecto Global?
            </h2>
            <p className="text-gray-600 leading-relaxed">
              We collaborate with quality-focused Indian manufacturers looking
              to export their products internationally. Our global network and
              compliance expertise help you reach premium markets while we
              handle the complexities of international trade.
            </p>
          </div>
          <div className="grid md:grid-cols-2 gap-8">
            {benefits.map((benefit, index) => {
              const Icon = benefit.icon;
              return (
                <Card key={index} className="border-0 shadow-lg">
                  <CardContent className="p-8">
                    <div className="w-14 h-14 bg-[#B8860B]/10 rounded-lg flex items-center justify-center mb-4">
                      <Icon className="text-[#B8860B]" size={28} />
                    </div>
                    <h3 className="text-xl font-bold text-[#0B1C2D] mb-3">
                      {benefit.title}
                    </h3>
                    <p className="text-gray-600 leading-relaxed">
                      {benefit.description}
                    </p>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>
      </section>

      <section className="py-20 bg-[#F5F7FA]">
        <div className="max-w-360 mx-auto px-6">
          <div className="grid md:grid-cols-2 gap-12 items-center">
            <div>
              <div className="flex items-center gap-3 mb-6">
                <div className="w-12 h-12 bg-[#B8860B]/10 rounded-lg flex items-center justify-center">
                  <FileCheck className="text-[#B8860B]" size={24} />
                </div>
                <h2 className="text-3xl font-bold text-[#0B1C2D]">
                  Partnership Requirements
                </h2>
              </div>
              <p className="text-gray-600 mb-6 leading-relaxed">
                To ensure quality and compliance for our global buyers, we
                require the following from our manufacturing partners:
              </p>
            </div>
            <Card className="border-0 shadow-lg">
              <CardContent className="p-8">
                <div className="space-y-3">
                  {requirements.map((requirement, index) => (
                    <div key={index} className="flex items-start gap-3">
                      <CheckCircle2
                        className="text-[#B8860B] shrink-0 mt-1"
                        size={20}
                      />
                      <span className="text-gray-700">{requirement}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </section>

      <section className="py-20">
        <div className="max-w-360 mx-auto px-6">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-[#0B1C2D] mb-4">
              Simple Onboarding Process
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Our streamlined onboarding process ensures quick verification and
              integration
            </p>
          </div>
          <div className="grid md:grid-cols-5 gap-6">
            {onboardingSteps.map((step, index) => (
              <Card
                key={index}
                className="text-center border-2 hover:border-[#B8860B] transition-colors"
              >
                <CardContent className="p-6">
                  <div className="w-12 h-12 bg-[#B8860B] text-[#ffffff] rounded-full flex items-center justify-center font-bold text-lg mx-auto mb-3">
                    {step.step}
                  </div>
                  <h3 className="font-bold text-[#0B1C2D] mb-2">
                    {step.title}
                  </h3>
                  <p className="text-gray-600 text-sm">{step.description}</p>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </section>

      <section className="py-20 bg-[#F5F7FA]">
        <div className="max-w-360 mx-auto px-6">
          <div className="max-w-3xl mx-auto">
            <div className="text-center mb-12">
              <h2 className="text-3xl font-bold text-[#0B1C2D] mb-4">
                Apply as a Manufacturing Partner
              </h2>
              <p className="text-gray-600">
                Fill out the form below and our team will contact you within
                24-48 hours
              </p>
            </div>
            <Card className="border-0 shadow-lg">
              <CardContent className="p-4 md:p-8">
                <form onSubmit={handleSubmit} className="space-y-6">
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <Label htmlFor="companyName">Company Name *</Label>
                      <Input
                        id="companyName"
                        name="companyName"
                        value={formState.companyName}
                        onChange={handleChange}
                        placeholder="Your company name"
                        className="mt-2"
                        disabled={isSubmitting}
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="contactPerson">Contact Person *</Label>
                      <Input
                        id="contactPerson"
                        name="contactPerson"
                        value={formState.contactPerson}
                        onChange={handleChange}
                        placeholder="Full name"
                        className="mt-2"
                        disabled={isSubmitting}
                        required
                      />
                    </div>
                  </div>
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <Label htmlFor="email">Email Address *</Label>
                      <Input
                        id="email"
                        name="email"
                        type="email"
                        value={formState.email}
                        onChange={handleChange}
                        placeholder="your@email.com"
                        className="mt-2"
                        disabled={isSubmitting}
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="phone">Phone Number *</Label>
                      <Input
                        id="phone"
                        name="phone"
                        type="tel"
                        value={formState.phone}
                        onChange={handleChange}
                        placeholder="+91 1234567890"
                        className="mt-2"
                        disabled={isSubmitting}
                        required
                        maxLength={20}
                      />
                    </div>
                  </div>
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <Label htmlFor="location">Location/City *</Label>
                      <Input
                        id="location"
                        name="location"
                        value={formState.location}
                        onChange={handleChange}
                        placeholder="City, State"
                        className="mt-2"
                        disabled={isSubmitting}
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="productCategory">
                        Product Category *
                      </Label>
                      <select
                        id="productCategory"
                        name="productCategory"
                        value={formState.productCategory}
                        onChange={handleChange}
                        required
                        disabled={isSubmitting}
                        className="mt-2 w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-[#B8860B] disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        <option value="">Select a category</option>
                        {productCategories.map((category) => (
                          <option key={category} value={category}>
                            {category}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="products">Products You Manufacture *</Label>
                    <Textarea
                      id="products"
                      name="products"
                      value={formState.products}
                      onChange={handleChange}
                      placeholder="List the main products you manufacture"
                      className="mt-2"
                      rows={3}
                      disabled={isSubmitting}
                      required
                    />
                  </div>
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <Label htmlFor="gst">GST Number *</Label>
                      <Input
                        id="gst"
                        name="gst"
                        value={formState.gst}
                        onChange={handleChange}
                        placeholder="GST registration number"
                        className="mt-2"
                        disabled={isSubmitting}
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="iec">IEC Number *</Label>
                      <Input
                        id="iec"
                        name="iec"
                        value={formState.iec}
                        onChange={handleChange}
                        placeholder="Import Export Code"
                        className="mt-2"
                        disabled={isSubmitting}
                        required
                      />
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="certifications">Certifications *</Label>
                    <Input
                      id="certifications"
                      name="certifications"
                      value={formState.certifications}
                      onChange={handleChange}
                      placeholder="ISO, GMP, FSSAI, etc."
                      className="mt-2"
                      disabled={isSubmitting}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="productionCapacity">
                      Monthly Production Capacity *
                    </Label>
                    <Input
                      id="productionCapacity"
                      name="productionCapacity"
                      value={formState.productionCapacity}
                      onChange={handleChange}
                      placeholder="e.g., 100 MT/month"
                      className="mt-2"
                      disabled={isSubmitting}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="message">Additional Information *</Label>
                    <Textarea
                      id="message"
                      name="message"
                      value={formState.message}
                      onChange={handleChange}
                      placeholder="Any additional details about your company or products"
                      className="mt-2"
                      rows={4}
                      disabled={isSubmitting}
                      required
                    />
                  </div>

                  {/* CAPTCHA Section */}
                  <div className="space-y-2">
                    <Label>Security Verification *</Label>
                    <div className="flex items-center gap-3 flex-wrap">
                      <div className="bg-gray-100 border rounded-md px-4 py-2 font-mono text-lg">
                        {numberCaptcha.num1} + {numberCaptcha.num2} = ?
                      </div>
                      <Input
                        type="number"
                        value={numberCaptcha.answer}
                        onChange={(e) => {
                          setNumberCaptcha((prev) => ({
                            ...prev,
                            answer: e.target.value,
                          }));
                          validateNumberCaptcha(e.target.value);
                        }}
                        disabled={isSubmitting}
                        className="w-20 text-center"
                        placeholder="?"
                        required
                      />
                      <Button
                        type="button"
                        variant="outline"
                        onClick={generateNumberCaptcha}
                        disabled={isSubmitting}
                        className="px-3"
                      >
                        ↻
                      </Button>
                    </div>
                    {numberCaptchaValid ? (
                      <p className="text-green-600 text-sm">
                        ✓ Correct! Form is ready to submit.
                      </p>
                    ) : (
                      numberCaptcha.answer && (
                        <p className="text-red-600 text-sm">
                          Please complete the captcha correctly
                        </p>
                      )
                    )}
                  </div>

                  <Button
                    type="submit"
                    className="w-full bg-[#B8860B] hover:bg-[#9A7209] text-[#ffffff] cursor-pointer"
                    size="lg"
                    disabled={isSubmitting || !numberCaptchaValid}
                  >
                    {isSubmitting ? (
                      <>
                        <span
                          className="spinner-border spinner-border-sm me-2"
                          role="status"
                          aria-hidden="true"
                        ></span>
                        Submitting...
                      </>
                    ) : (
                      <>
                        Submit Application
                        <Send className="ml-2" size={18} />
                      </>
                    )}
                  </Button>
                  <p className="text-sm text-gray-500 text-center">
                    By submitting this form, you agree to our terms and
                    conditions
                  </p>
                </form>
              </CardContent>
            </Card>
          </div>
        </div>
      </section>

      <section className="py-20 bg-[#0B1C2D] text-[#ffffff]">
        <div className="max-w-360 mx-auto px-6 text-center">
          <h2 className="text-4xl font-bold mb-4">
            Questions About Partnership?
          </h2>
          <p className="text-gray-300 mb-8 max-w-2xl mx-auto">
            Our team is available to answer any questions about becoming a
            manufacturing partner.
          </p>
          <Link href="/contact">
            <Button
              size="lg"
              className="bg-[#B8860B] hover:bg-[#9A7209] text-[#ffffff] cursor-pointer"
            >
              Contact Our Team
            </Button>
          </Link>
        </div>
      </section>
    </div>
  );
}
