"use client";

import { useState } from "react";
import Image from "next/image";
import { motion, AnimatePresence } from "framer-motion";
import { Baby, Scale, Sparkles, Zap, AlertCircle, RotateCcw, MessageCircle } from "lucide-react";
import { useTranslation } from "@/lib/i18n/context";
import { SectionHeading } from "@/components/ui/section-heading";

interface RecommendationResult {
  sizeIndex: number;
  skinTip: string;
  activityTip: string;
}

function getRecommendation(
  weight: number,
  sensitivityIndex: number,
  activityIndex: number,
  tips: { low: string; medium: string; high: string },
  activityTips: { low: string; medium: string; high: string }
): RecommendationResult {
  let sizeIndex = 0;
  if (weight <= 5) sizeIndex = 0;
  else if (weight <= 6) sizeIndex = 1;
  else if (weight <= 9) sizeIndex = 2;
  else if (weight <= 18) sizeIndex = 3;
  else if (weight <= 25) sizeIndex = 4;
  else sizeIndex = 5;

  const skinKeys: (keyof typeof tips)[] = ["low", "medium", "high"];
  const actKeys: (keyof typeof activityTips)[] = ["low", "medium", "high"];

  return {
    sizeIndex,
    skinTip: tips[skinKeys[sensitivityIndex]],
    activityTip: activityTips[actKeys[activityIndex]],
  };
}

export function DiaperAdvisor() {
  const { t, dir } = useTranslation();
  const [ageIndex, setAgeIndex] = useState(0);
  const [weight, setWeight] = useState("");
  const [sensitivityIndex, setSensitivityIndex] = useState(0);
  const [activityIndex, setActivityIndex] = useState(0);
  const [result, setResult] = useState<RecommendationResult | null>(null);

  const handleSubmit = () => {
    const w = parseFloat(weight);
    if (isNaN(w) || w <= 0) return;
    const rec = getRecommendation(w, sensitivityIndex, activityIndex, t.advisor.tips, t.advisor.activityTips);
    setResult(rec);
  };

  const handleReset = () => {
    setAgeIndex(0);
    setWeight("");
    setSensitivityIndex(0);
    setActivityIndex(0);
    setResult(null);
  };

  const sizes = t.products.sizes;

  return (
    <section className="section-padding bg-white relative" dir={dir}>
      <div className="max-w-4xl mx-auto">
        <SectionHeading
          tag={t.advisor.sectionTag}
          title={t.advisor.title}
          subtitle={t.advisor.subtitle}
        />

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5 }}
          className="bg-gradient-to-br from-baby-blue/20 via-soft-cream/30 to-white rounded-3xl border border-primary/10 p-6 md:p-10 shadow-sm"
        >
          <AnimatePresence mode="wait">
            {!result ? (
              <motion.div
                key="form"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0, x: -20 }}
                className="space-y-6"
              >
                {/* Baby Age */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-bold text-dark-text mb-2">
                    <Baby size={16} className="text-primary" />
                    {t.advisor.babyAge}
                  </label>
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                    {t.advisor.ages.map((age, i) => (
                      <button
                        key={i}
                        onClick={() => setAgeIndex(i)}
                        className={`px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                          ageIndex === i
                            ? "bg-primary text-white shadow-md"
                            : "bg-white/80 text-dark-text/60 hover:bg-primary/10 border border-medium-gray/50"
                        }`}
                      >
                        {age}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Baby Weight */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-bold text-dark-text mb-2">
                    <Scale size={16} className="text-primary" />
                    {t.advisor.babyWeight}
                  </label>
                  <input
                    type="number"
                    min="1"
                    max="30"
                    value={weight}
                    onChange={(e) => setWeight(e.target.value)}
                    className="w-full px-5 py-3 rounded-xl border border-medium-gray/50 bg-white/80 text-dark-text focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all text-sm"
                    placeholder="e.g. 5"
                  />
                </div>

                {/* Skin Sensitivity */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-bold text-dark-text mb-2">
                    <Sparkles size={16} className="text-primary" />
                    {t.advisor.skinSensitivity}
                  </label>
                  <div className="grid grid-cols-3 gap-2">
                    {t.advisor.sensitivity.map((level, i) => (
                      <button
                        key={i}
                        onClick={() => setSensitivityIndex(i)}
                        className={`px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                          sensitivityIndex === i
                            ? "bg-primary text-white shadow-md"
                            : "bg-white/80 text-dark-text/60 hover:bg-primary/10 border border-medium-gray/50"
                        }`}
                      >
                        {level}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Activity Level */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-bold text-dark-text mb-2">
                    <Zap size={16} className="text-primary" />
                    {t.advisor.activityLevel}
                  </label>
                  <div className="grid grid-cols-3 gap-2">
                    {t.advisor.activity.map((level, i) => (
                      <button
                        key={i}
                        onClick={() => setActivityIndex(i)}
                        className={`px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                          activityIndex === i
                            ? "bg-primary text-white shadow-md"
                            : "bg-white/80 text-dark-text/60 hover:bg-primary/10 border border-medium-gray/50"
                        }`}
                      >
                        {level}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Submit */}
                <button
                  onClick={handleSubmit}
                  disabled={!weight}
                  className="w-full btn-primary py-4 text-base disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:transform-none"
                >
                  {t.advisor.getRecommendation}
                </button>
              </motion.div>
            ) : (
              <motion.div
                key="result"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0 }}
                className="space-y-6"
              >
                {/* Result Card */}
                <div className="text-center">
                  <p className="text-sm font-semibold text-primary mb-2">
                    {t.advisor.resultTitle}
                  </p>
                  <div className="inline-flex flex-col items-center bg-white rounded-3xl p-8 shadow-lg border border-primary/10">
                    <Image
                      src={sizes[result.sizeIndex].image}
                      alt={sizes[result.sizeIndex].name}
                      width={150}
                      height={165}
                      className="h-36 w-auto object-contain mb-4"
                    />
                    <div className="w-12 h-12 rounded-full bg-primary text-white flex items-center justify-center text-2xl font-black mb-2">
                      {sizes[result.sizeIndex].number}
                    </div>
                    <h3 className="text-2xl font-extrabold text-dark-text">
                      {sizes[result.sizeIndex].name}
                    </h3>
                    <p className="text-sm font-semibold text-primary">
                      {sizes[result.sizeIndex].weight}
                    </p>
                  </div>
                </div>

                {/* Care Tips */}
                <div className="bg-white/80 rounded-2xl p-6 space-y-3">
                  <h4 className="text-sm font-bold text-dark-text flex items-center gap-2">
                    <Sparkles size={16} className="text-soft-teal" />
                    {t.advisor.careTips}
                  </h4>
                  <p className="text-sm text-dark-text/70 leading-relaxed">• {result.skinTip}</p>
                  <p className="text-sm text-dark-text/70 leading-relaxed">• {result.activityTip}</p>
                </div>

                {/* WhatsApp Order Button */}
                <button
                  onClick={() => {
                    const msg = `Hello, the UNIPAM Diaper Advisor recommended ${sizes[result.sizeIndex].name} (${sizes[result.sizeIndex].weight}) for my baby. I would like to inquire about availability.`;
                    window.open(`https://wa.me/905352534344?text=${encodeURIComponent(msg)}`, "_blank");
                  }}
                  className="w-full flex items-center justify-center gap-3 py-4 rounded-2xl bg-[#25D366] text-white font-bold text-base hover:opacity-90 transition-opacity shadow-lg shadow-[#25D366]/20"
                >
                  <MessageCircle size={22} />
                  {dir === "rtl" ? "اطلب عبر واتساب" : "Order via WhatsApp"}
                </button>

                {/* Disclaimer */}
                <div className="flex gap-3 p-4 bg-warm-coral/5 rounded-xl border border-warm-coral/10">
                  <AlertCircle size={18} className="text-warm-coral flex-shrink-0 mt-0.5" />
                  <p className="text-xs text-dark-text/60 leading-relaxed">
                    {t.advisor.disclaimer}
                  </p>
                </div>

                {/* Reset */}
                <button
                  onClick={handleReset}
                  className="w-full flex items-center justify-center gap-2 py-3 rounded-full bg-light-gray text-dark-text/70 font-bold text-sm hover:bg-primary/10 hover:text-primary transition-all"
                >
                  <RotateCcw size={16} />
                  {t.advisor.reset}
                </button>
              </motion.div>
            )}
          </AnimatePresence>
        </motion.div>
      </div>
    </section>
  );
}
