"use client";

import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowUpRight,
  Sparkles,
  Users,
  BrainCircuit,
  ShieldCheck,
  BarChart3,
  Building2,
  CheckCircle2,
} from "lucide-react";

const fadeUp = {
  hidden: { y: 30, opacity: 0 },
  visible: (i: number) => ({
    y: 0,
    opacity: 1,
    transition: { delay: i * 0.1, duration: 0.6, ease: [0.21, 0.45, 0.32, 0.9] as const },
  }),
};

const valueProps = [
  {
    icon: Users,
    title: "Access Farmer Pipeline",
    description:
      "Tap into a verified pipeline of smallholder farmers with digital identities, GIS-mapped land, and documented crop histories.",
  },
  {
    icon: BrainCircuit,
    title: "ML-Scored Applications",
    description:
      "Receive pre-scored loan applications using satellite imagery, yield data, and alternative credit signals — reducing your underwriting cost.",
  },
  {
    icon: ShieldCheck,
    title: "Digital Compliance",
    description:
      "Automated eKYC, AML checks, and regulatory documentation packaged with every farmer application for streamlined due diligence.",
  },
  {
    icon: BarChart3,
    title: "SLA Monitoring",
    description:
      "Real-time dashboards tracking application status, disbursement timelines, escalation paths, and institutional performance metrics.",
  },
];

const roles = [
  "Bank / Lender",
  "Microfinance Institution",
  "Agricultural Cooperative",
  "Buyer / Exporter",
  "Government Agency",
  "Technology Partner",
  "Other",
];

const partnerLogos = [
  "Partner Bank",
  "Regional MFI",
  "AgriCoop Union",
  "Export Corp",
  "Gov Agency",
  "Tech Partner",
];

export default function PartnerPage() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    name: "",
    organization: "",
    email: "",
    role: "",
    message: "",
  });

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      const res = await fetch("/api/partner/inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => null);
        const message =
          data?.error?.message || data?.message || "Failed to submit inquiry. Please try again.";
        throw new Error(message);
      }

      setSubmitted(true);
      setFormData({ name: "", organization: "", email: "", role: "", message: "" });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to submit inquiry. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="min-h-screen bg-white">
      {/* Hero */}
      <section className="relative w-full overflow-hidden bg-gradient-to-b from-[#f0f9f4] to-white pt-24 pb-20 lg:pt-32 lg:pb-28">
        <div className="absolute inset-0 pointer-events-none opacity-30">
          <div className="absolute top-0 right-1/4 w-[500px] h-[500px] rounded-full bg-[#198F38]/10 blur-[120px]" />
          <div className="absolute bottom-0 left-1/4 w-[400px] h-[400px] rounded-full bg-[#198F38]/5 blur-[100px]" />
        </div>

        <div className="relative z-10 max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <motion.div
            initial="hidden"
            animate="visible"
            custom={0}
            variants={fadeUp}
            className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full border border-[#198F38]/15 bg-[#198F38]/5 mb-6"
          >
            <Building2 className="w-4 h-4 text-[#198F38]" />
            <span className="font-inter text-sm font-medium text-[#198F38]">
              Institutional Partnerships
            </span>
          </motion.div>

          <motion.h1
            initial="hidden"
            animate="visible"
            custom={1}
            variants={fadeUp}
            className="font-onest text-4xl sm:text-5xl lg:text-6xl font-semibold leading-tight tracking-tight text-[#042718]"
          >
            Partner with{" "}
            <span className="font-playfair italic text-[#042718]/40">
              AGNET
            </span>
          </motion.h1>

          <motion.p
            initial="hidden"
            animate="visible"
            custom={2}
            variants={fadeUp}
            className="mt-5 max-w-2xl mx-auto font-inter text-lg lg:text-xl text-[#042718]/70 leading-relaxed"
          >
            For banks, MFIs, cooperatives, and buyers — connect to
            Uzbekistan&apos;s agricultural economy through a single integration
            layer with verified farmer data and ML-powered credit intelligence.
          </motion.p>
        </div>
      </section>

      {/* Value Proposition Cards */}
      <section className="w-full py-20 lg:py-28 bg-white">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <motion.div
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true }}
            custom={0}
            variants={fadeUp}
            className="text-center mb-14"
          >
            <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full border border-[#198F38]/15 bg-[#198F38]/5 mb-4">
              <Sparkles className="w-4 h-4 text-[#198F38]" />
              <span className="font-inter text-sm font-medium text-[#198F38]">
                Why Partner
              </span>
            </div>
            <h2 className="font-onest text-3xl sm:text-4xl lg:text-[44px] font-semibold tracking-tight text-[#042718]">
              What AGNET delivers for institutions
            </h2>
          </motion.div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            {valueProps.map((item, idx) => (
              <motion.div
                key={item.title}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true }}
                custom={idx + 1}
                variants={fadeUp}
                className="group rounded-2xl border border-[#042718]/8 bg-white p-6 lg:p-8 hover:border-[#198F38]/20 hover:shadow-lg transition-all duration-300"
              >
                <div className="w-11 h-11 rounded-xl bg-[#198F38]/5 border border-[#198F38]/15 flex items-center justify-center mb-5 group-hover:bg-[#198F38]/10 transition-colors">
                  <item.icon className="w-5 h-5 text-[#198F38]" />
                </div>
                <h3 className="font-onest text-lg font-semibold text-[#042718]">
                  {item.title}
                </h3>
                <p className="mt-2 font-inter text-[15px] leading-relaxed text-[#042718]/65">
                  {item.description}
                </p>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* Partner Logos */}
      <section className="w-full py-14 bg-[#FAFCFB]">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <motion.p
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true }}
            custom={0}
            variants={fadeUp}
            className="text-center font-inter text-sm font-medium text-[#042718]/40 uppercase tracking-wider mb-8"
          >
            Designed for leading institutions
          </motion.p>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
            {partnerLogos.map((name, idx) => (
              <motion.div
                key={name}
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true }}
                custom={idx}
                variants={fadeUp}
                className="h-16 rounded-xl border border-[#042718]/6 bg-white flex items-center justify-center"
              >
                <span className="font-inter text-sm font-medium text-[#042718]/30">
                  {name}
                </span>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* Lead Capture Form */}
      <section className="w-full py-20 lg:py-28 bg-white">
        <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
          <motion.div
            initial="hidden"
            whileInView="visible"
            viewport={{ once: true }}
            custom={0}
            variants={fadeUp}
            className="text-center mb-10"
          >
            <h2 className="font-onest text-3xl sm:text-4xl font-semibold tracking-tight text-[#042718]">
              Get in touch
            </h2>
            <p className="mt-3 font-inter text-base text-[#042718]/60">
              Tell us about your organization and we&apos;ll reach out to discuss
              integration.
            </p>
          </motion.div>

          <AnimatePresence mode="wait">
            {submitted ? (
              <motion.div
                key="success"
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                className="rounded-2xl border border-[#198F38]/20 bg-[#198F38]/5 p-8 text-center"
              >
                <CheckCircle2 className="w-12 h-12 text-[#198F38] mx-auto mb-4" />
                <h3 className="font-onest text-xl font-semibold text-[#042718]">
                  Thank you!
                </h3>
                <p className="mt-2 font-inter text-[15px] text-[#042718]/65">
                  We&apos;ve received your inquiry. Our partnerships team will
                  be in touch within 2 business days.
                </p>
                <button
                  onClick={() => setSubmitted(false)}
                  className="mt-6 font-inter text-sm font-medium text-[#198F38] hover:underline"
                >
                  Submit another inquiry
                </button>
              </motion.div>
            ) : (
              <motion.form
                key="form"
                initial="hidden"
                whileInView="visible"
                viewport={{ once: true }}
                custom={1}
                variants={fadeUp}
                onSubmit={handleSubmit}
                className="space-y-5"
              >
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                  <div>
                    <label
                      htmlFor="partner-name"
                      className="block font-inter text-sm font-medium text-[#042718]/80 mb-1.5"
                    >
                      Full Name
                    </label>
                    <input
                      id="partner-name"
                      type="text"
                      required
                      value={formData.name}
                      onChange={(e) =>
                        setFormData({ ...formData, name: e.target.value })
                      }
                      className="w-full px-4 py-3 rounded-xl border border-[#042718]/10 bg-white font-inter text-sm text-[#042718] placeholder:text-[#042718]/30 focus:outline-none focus:border-[#198F38]/40 focus:ring-1 focus:ring-[#198F38]/20 transition-colors"
                      placeholder="Your name"
                    />
                  </div>
                  <div>
                    <label
                      htmlFor="partner-org"
                      className="block font-inter text-sm font-medium text-[#042718]/80 mb-1.5"
                    >
                      Organization
                    </label>
                    <input
                      id="partner-org"
                      type="text"
                      required
                      value={formData.organization}
                      onChange={(e) =>
                        setFormData({ ...formData, organization: e.target.value })
                      }
                      className="w-full px-4 py-3 rounded-xl border border-[#042718]/10 bg-white font-inter text-sm text-[#042718] placeholder:text-[#042718]/30 focus:outline-none focus:border-[#198F38]/40 focus:ring-1 focus:ring-[#198F38]/20 transition-colors"
                      placeholder="Company or institution"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                  <div>
                    <label
                      htmlFor="partner-email"
                      className="block font-inter text-sm font-medium text-[#042718]/80 mb-1.5"
                    >
                      Email
                    </label>
                    <input
                      id="partner-email"
                      type="email"
                      required
                      value={formData.email}
                      onChange={(e) =>
                        setFormData({ ...formData, email: e.target.value })
                      }
                      className="w-full px-4 py-3 rounded-xl border border-[#042718]/10 bg-white font-inter text-sm text-[#042718] placeholder:text-[#042718]/30 focus:outline-none focus:border-[#198F38]/40 focus:ring-1 focus:ring-[#198F38]/20 transition-colors"
                      placeholder="you@company.com"
                    />
                  </div>
                  <div>
                    <label
                      htmlFor="partner-role"
                      className="block font-inter text-sm font-medium text-[#042718]/80 mb-1.5"
                    >
                      Role
                    </label>
                    <select
                      id="partner-role"
                      required
                      value={formData.role}
                      onChange={(e) =>
                        setFormData({ ...formData, role: e.target.value })
                      }
                      className="w-full px-4 py-3 rounded-xl border border-[#042718]/10 bg-white font-inter text-sm text-[#042718] focus:outline-none focus:border-[#198F38]/40 focus:ring-1 focus:ring-[#198F38]/20 transition-colors appearance-none"
                    >
                      <option value="" disabled>
                        Select your role
                      </option>
                      {roles.map((role) => (
                        <option key={role} value={role}>
                          {role}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                <div>
                  <label
                    htmlFor="partner-message"
                    className="block font-inter text-sm font-medium text-[#042718]/80 mb-1.5"
                  >
                    Message
                  </label>
                  <textarea
                    id="partner-message"
                    rows={4}
                    value={formData.message}
                    onChange={(e) =>
                      setFormData({ ...formData, message: e.target.value })
                    }
                    className="w-full px-4 py-3 rounded-xl border border-[#042718]/10 bg-white font-inter text-sm text-[#042718] placeholder:text-[#042718]/30 focus:outline-none focus:border-[#198F38]/40 focus:ring-1 focus:ring-[#198F38]/20 transition-colors resize-none"
                    placeholder="Tell us about your goals and how you'd like to partner..."
                  />
                </div>

                <button
                  type="submit"
                  disabled={submitting}
                  className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-[#042718] text-white font-inter font-medium text-base hover:bg-[#042718]/90 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
                >
                  {submitting ? "Submitting..." : "Submit Inquiry"}
                  <ArrowUpRight className="w-4 h-4" />
                </button>
                {error && (
                  <p className="font-inter text-sm text-red-600 text-center">{error}</p>
                )}
              </motion.form>
            )}
          </AnimatePresence>
        </div>
      </section>
    </main>
  );
}
