"use client"

import { useState, useEffect, useMemo } from "react"
import Link from "next/link"
import { Check, Star, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { getStoredCountryCode, getPlanPrice, formatMoney, getPlanSaving, getCurrencyCode } from "@/lib/planHelpers"
import { handleSignupFlow } from "@/lib/cookies"

// Plan Data Types
type CurriculumOption = {
  name: string
  annual: string
  monthly: string
  quarterly: string
}

type Plan = {
  name: string
  audience: string
  annual?: string
  monthly?: string
  save?: string
  highlight?: boolean
  features: string[]
  cta: "signup" | "buy" | "quote-modal"
  curriculumOptions?: CurriculumOption[]
}

const commonPlans: Plan[] = [
  {
    name: "Free",
    audience: "For getting started",
    annual: "Free",
    monthly: "Free",
    features: [
      "5 video / audio files & links",
      "5 PDF / Word / text files",
      "Single file processing at a time",
      "40+ languages supported",
      "Short & detailed summaries",
      "3-level mindmaps & quizzes",
      "Voice over text support",
      "iQuery on your content",
    ],
    cta: "signup",
  },
  {
    name: "Basic",
    audience: "For individual users",
    annual: "₹4,950",
    monthly: "₹495",
    save: "Save 20%",
    features: [
      "25 video / audio files",
      "60 PDF / Word / files",
      "40+ languages supported",
      "Short + detailed summaries",
      "3-level mindmaps & quizzes",
      "Cross lingual, Voiceover text",
      "iQuery on your own content",
      "Mobile & web app",
    ],
    cta: "buy",
  },
]

const plansData: Record<string, Plan[]> = {
  student: [
    ...commonPlans,
    {
      name: "Student Curriculum Library",
      audience: "Mapped to your board",
      annual: "₹5,950",
      monthly: "₹595",
      highlight: true,
      curriculumOptions: [
        { name: "CBSE", annual: "₹5,950", monthly: "₹595", quarterly: "₹1,595" },
        { name: "MHB", annual: "₹5,950", monthly: "₹595", quarterly: "₹1,595" },
        { name: "IGCSE", annual: "₹5,950", monthly: "₹595", quarterly: "₹1,595" },
        { name: "ITI", annual: "₹2,450", monthly: "₹245", quarterly: "₹675" },
        { name: "Nursing", annual: "₹2,950", monthly: "₹295", quarterly: "₹795" }
      ],
      features: [
        "10 video / audio files & links per month",
        "20 PDF / Word / text files per month",
        "All facilities Basic plan",
        "Choose your specific curriculum",
      ],
      cta: "buy",
    },
  ],
  research: [
    {
      name: "Free Research",
      audience: "For getting started",
      annual: "Free",
      monthly: "Free",
      features: [
        "5 video / audio files & links",
        "5 PDF / Word / text files",
        "Single file processing at a time",
        "40+ languages supported",
        "Short & detailed summaries",
        "3-level mindmaps & quizzes",
        "Voice over text support",
        "iQuery on your content",
      ],
      cta: "signup",
    },
    {
      name: "Research",
      audience: "For analysts & scholars",
      annual: "₹9,950",
      monthly: "₹995",
      save: "Save 20%",
      highlight: true,
      features: [
        "40 video / audio files & links per month",
        "100 PDF / Word / text files per month",
        "Many input files at once",
        "All Basic facilities",
        "Similarity & gap analysis",
        "Statistical analysis",
        "Query multiple files simultaneously",
        "Consolidated mindmaps & analysis",
        "Multi-modal analysis & reports",
      ],
      cta: "buy",
    },
  ],
  education: [
    {
      name: "Faculty",
      audience: "For teaching staff",
      save: "Save 20%",
      features: [
        "50 video / audio files & links per month",
        "100 PDF / Word / text files per month",
        "All Basic facilities",
        "Course objectives & outcomes",
        "Lesson objectives & outcomes",
        "Competency mapping",
        "Multiple assessment types",
        "Test papers as per weights",
      ],
      cta: "quote-modal",
    },
    {
      name: "Department Head",
      audience: "For department heads",
      save: "Save 20%",
      features: [
        "Everything From Faculty",
        "Programe Objectives/Outcomes",
        "PO-CO Mapping",
        "PO-CO Attainment",
        "Gap Analysis",
        "Programme / Course Evaluation",
        "Continous Assessment & Attainment Module (optional)",
      ],
      cta: "quote-modal",
    },
  ],
  market: [
    {
      name: "Market Research",
      audience: "For research teams",
      highlight: true,
      features: [
        "Unlimited media & document inputs",
        "All Basic facilities",
        "Theme merge / demerge & consolidation",
        "Automated 3-level thematic analysis",
        "10+ chart, graph & network diagram types",
        "Statistical analysis of survey data",
        "Large sample sizes supported",
        "Detailed reports",
      ],
      cta: "quote-modal",
    },
  ],
}

const mainTabs = [
  { id: "student", label: "Student" },
  { id: "education", label: "Education" },
  { id: "research", label: "Research" },
  { id: "market", label: "Market Research" },
]

const studentSubs = [
  { id: "document-analyze", label: "Document Analyze" },
  { id: "cbse", label: "CBSE" },
  { id: "mhb", label: "MHB" },
  { id: "igcse", label: "IGCSE" },
  { id: "iti", label: "ITI" },
  { id: "nursing", label: "Nursing" },
]

const educationSubs = [
  { id: "faculty", label: "Faculty" },
  { id: "dept", label: "Dept Head" },
]

export default function PlansPage() {
  const [activeTab, setActiveTab] = useState("student")
  const [activeStudentSub, setActiveStudentSub] = useState("document-analyze")
  const [activeEduSub, setActiveEduSub] = useState("faculty")
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [selectedPlan, setSelectedPlan] = useState("")
  const [countryCode, setCountryCode] = useState<string>("IN")
  const [billingCycles, setBillingCycles] = useState<Record<number, string>>({})

  useEffect(() => {
    const sectionMap: Record<string, string> = {
      individual: "student",
      individuals: "student",
      student: "student",
      education: "education",
      research: "research",
      market: "market",
      "market-research": "market",
    }

    const params = new URLSearchParams(window.location.search)
    const requestedSection = params.get("section") || window.location.hash.replace("#", "")
    const tab = sectionMap[requestedSection.toLowerCase()]

    if (tab) {
      setActiveTab(tab)
    }
  }, [])

  useEffect(() => {
    const fetchCountry = async () => {
      let code = localStorage.getItem("country")
      if (code) {
        setCountryCode(code.toUpperCase())
        return
      }

      try {
        const res = await fetch("https://ipapi.co/json/")
        const data = await res.json()
        if (data && data.country_code) {
          const fetchedCode = data.country_code.toUpperCase()
          localStorage.setItem("country", fetchedCode)
          setCountryCode(fetchedCode)
          return
        }
      } catch (err) {
        console.error("Failed to fetch from ipapi.co, trying fallback...", err)
      }

      try {
        const res = await fetch("https://freeipapi.com/api/json")
        const data = await res.json()
        if (data && data.countryCode) {
          const fetchedCode = data.countryCode.toUpperCase()
          localStorage.setItem("country", fetchedCode)
          setCountryCode(fetchedCode)
          return
        }
      } catch (err) {
        console.error("Failed to fetch from freeipapi.com", err)
      }
    }

    fetchCountry()
  }, [])

  const openModal = (planName: string) => {
    setSelectedPlan(planName)
    setIsModalOpen(true)
  }

  const closeModal = () => setIsModalOpen(false)

  const getDynamicPlans = (plans: Plan[], code: string): Plan[] => {
    const resolvePrice = (planId: string, type: 'Month' | 'Quarter' | 'Year', defaultValue: string) => {
      const price = getPlanPrice(planId, type, code)
      if (price === null || price === undefined) return defaultValue
      if (price === "0" || Number(price) === 0) return "Free"
      return formatMoney(price, getCurrencyCode(code))
    }

    const resolveSaving = (planId: string, type: 'Month' | 'Quarter' | 'Year', defaultValue: string) => {
      const saving = getPlanSaving(planId, type)
      return saving ? `Save ${saving}` : defaultValue
    }

    return plans.map(plan => {
      if (plan.name === "Free") {
        return { ...plan, annual: "Free", monthly: "Free" }
      }
      if (plan.name === "Basic") {
        return {
          ...plan,
          annual: resolvePrice("3", "Year", "₹4,950"),
          monthly: resolvePrice("3", "Month", "₹495"),
          save: resolveSaving("3", "Year", "Save 20%")
        }
      }
      if (plan.name === "Student Curriculum Library") {
        return {
          ...plan,
          annual: resolvePrice("6", "Year", "₹5,950"),
          monthly: resolvePrice("6", "Month", "₹595"),
          curriculumOptions: plan.curriculumOptions?.map(opt => {
            let planId = "6"
            if (opt.name === "CBSE") planId = "6"
            else if (opt.name === "MHB") planId = "7"
            else if (opt.name === "IGCSE") planId = "8"
            else if (opt.name === "ITI") planId = "9"
            else if (opt.name === "Nursing") planId = "11"
            return {
              ...opt,
              annual: resolvePrice(planId, "Year", opt.annual),
              monthly: resolvePrice(planId, "Month", opt.monthly),
              quarterly: resolvePrice(planId, "Quarter", opt.quarterly)
            }
          })
        }
      }
      if (plan.name === "Research" || plan.name === "Professional") {
        return {
          ...plan,
          annual: resolvePrice("10", "Year", "₹9,950"),
          monthly: resolvePrice("10", "Month", "₹995"),
          save: resolveSaving("10", "Year", "Save 20%")
        }
      }
      return plan
    })
  }

  const dynamicPlansData = useMemo(() => {
    const data: Record<string, Plan[]> = {}
    Object.keys(plansData).forEach(key => {
      data[key] = getDynamicPlans(plansData[key], countryCode)
    })
    return data
  }, [countryCode])

  const currentPlans = dynamicPlansData[activeTab] || []

  return (
    <div className="min-h-screen bg-background">
      <section id="plans" className="pt-6 pb-4 bg-gradient-to-b from-muted/50 to-background scroll-mt-24">
        <div className="mx-auto max-w-4xl px-4 lg:px-8 text-center">
          <h1 className="text-3xl sm:text-4xl font-bold text-foreground mb-2">
            Choose your plan
          </h1>
          <p className="text-base text-muted-foreground mb-1">
            Start free for 10 days. Upgrade anytime. Save 20% on annual billing.
          </p>
          <p className="text-sm text-muted-foreground">
            No credit card required.
          </p>
        </div>

        {/* Main Tabs */}
        <div className="mt-4 flex justify-center">
          <div className="inline-flex p-1 bg-muted rounded-xl shadow-inner max-w-full overflow-x-auto">
            {mainTabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => {
                  setActiveTab(tab.id)
                  window.history.replaceState(null, "", `/plans?section=${tab.id}#plans`)
                }}
                className={cn(
                  "px-4 sm:px-6 py-2.5 rounded-lg text-sm font-medium transition-all whitespace-nowrap",
                  activeTab === tab.id
                    ? "bg-background text-foreground shadow-sm"
                    : "text-muted-foreground hover:text-foreground"
                )}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>

        {/* Sub Tabs / Pills */}
        <div className="mt-4">
          {activeTab === "student" && (
            <div className="flex flex-wrap justify-center gap-2">
              {studentSubs.map((sub) => (
                <button
                  key={sub.id}
                  onClick={() => setActiveStudentSub(sub.id)}
                  className={cn(
                    "px-4 py-1.5 rounded-full text-sm font-medium border transition-all",
                    activeStudentSub === sub.id
                      ? "bg-primary text-primary-foreground border-primary shadow-md"
                      : "bg-background text-muted-foreground border-border hover:border-primary/50"
                  )}
                >
                  {sub.label}
                </button>
              ))}
            </div>
          )}
          {activeTab === "education" && (
            <div className="flex flex-wrap justify-center gap-2">
              {educationSubs.map((sub) => (
                <button
                  key={sub.id}
                  onClick={() => setActiveEduSub(sub.id)}
                  className={cn(
                    "px-4 py-1.5 rounded-full text-sm font-medium border transition-all",
                    activeEduSub === sub.id
                      ? "bg-primary text-primary-foreground border-primary shadow-md"
                      : "bg-background text-muted-foreground border-border hover:border-primary/50"
                  )}
                >
                  {sub.label}
                </button>
              ))}
            </div>
          )}
        </div>
      </section>

      <section className="py-4 bg-background">
        <div className="mx-auto max-w-7xl px-4 lg:px-8">
          <div
            className={cn(
              "flex flex-wrap justify-center gap-8 items-stretch mx-auto",
              activeTab === "student" ? "max-w-4xl" : "max-w-6xl"
            )}
          >
            {currentPlans.map((plan, index) => {
              // Special logic for curriculum based cards
              let displayAnnual = plan.annual
              let displayMonthly = plan.monthly
              let displayQuarterly = ""
              let displayName = plan.name
              let displayAudience = plan.audience
              if (
                activeTab === "student" &&
                plan.name === "Free" &&
                activeStudentSub !== "document-analyze"
              ) {
                displayName =
                  activeStudentSub === "cbse" ? "CBSE Free" :
                    activeStudentSub === "mhb" ? "MHB Free" :
                      activeStudentSub === "igcse" ? "IGCSE Free" :
                        activeStudentSub === "iti" ? "ITI Free" :
                          activeStudentSub === "nursing" ? "Nursing Free" :
                            "Free"

                displayAudience = "For getting started"
              }

              if (activeTab === "student") {
                // Document Analyze → hide curriculum card
                if (
                  activeStudentSub === "document-analyze" &&
                  plan.curriculumOptions
                ) {
                  return null
                }

                // Board selected → hide Basic plan
                if (
                  activeStudentSub !== "document-analyze" &&
                  plan.name === "Basic"
                ) {
                  return null
                }

                // Board selected → show only matching curriculum card
                if (plan.curriculumOptions) {
                  const opt = plan.curriculumOptions.find(
                    o => o.name.toLowerCase() === activeStudentSub.toLowerCase()
                  )

                  if (!opt) return null

                  displayAnnual = opt.annual
                  displayMonthly = opt.monthly
                  displayQuarterly = opt.quarterly
                  displayName = `${opt.name} Curriculum Pro`
                  displayAudience = `For ${opt.name} Students`
                }
              }

              // Filter logic for Education tab sub-pills
              if (activeTab === "education") {
                if (activeEduSub === "faculty" && plan.name === "Department Head") return null
                if (activeEduSub === "dept" && plan.name === "Faculty") return null
              }

              return (
                <div
                  key={index}
                  className={cn(
                    "relative flex flex-col bg-card rounded-2xl border p-8 shadow-sm transition-all hover:shadow-md w-full max-w-sm flex-1 basis-[350px] min-w-[300px]",
                    plan.highlight ? "border-primary/50 ring-1 ring-primary/20 scale-[1.02]" : "border-border"
                  )}
                >
                  {plan.highlight && (
                    <div className="absolute -top-4 left-1/2 -translate-x-1/2">
                      <span className="inline-flex items-center gap-1 px-3 py-1 text-xs font-bold bg-primary text-primary-foreground rounded-full shadow-lg">
                        <Star className="h-3 w-3 fill-current" /> Most Popular
                      </span>
                    </div>
                  )}

                  <div className="mb-6">
                    <h3 className="text-xl font-bold text-foreground mb-1">{displayName}</h3>
                    <p className="text-sm text-muted-foreground">{displayAudience}</p>
                  </div>

                  {displayMonthly && displayAnnual && (
                    <div className="mb-6">
                      <div className="flex items-baseline gap-1">
                        <span className="text-4xl font-bold text-foreground tracking-tight">
                          {(billingCycles[index] || "Month") === "Year" ? displayAnnual :
                            (billingCycles[index] === "Quarter" ? displayQuarterly : displayMonthly)}
                        </span>
                        {displayMonthly !== "Free" && (
                          <span className="text-sm text-muted-foreground">
                            / {(billingCycles[index] || "Month").toLowerCase()}
                          </span>
                        )}
                      </div>
                      {displayMonthly !== "Free" && (
                        <div className="mt-2 flex flex-col gap-2">
                          <select
                            className="w-full p-2 rounded-lg border border-border bg-background text-sm font-medium focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
                            value={billingCycles[index] || "Month"}
                            onChange={(e) => {
                              setBillingCycles(prev => ({ ...prev, [index]: e.target.value }))
                            }}
                          >
                            <option value="Month">Billed Monthly ({displayMonthly}/mo)</option>
                            <option value="Year">Billed Annually ({displayAnnual}/yr)</option>
                            {displayQuarterly && <option value="Quarter">Billed Quarterly ({displayQuarterly}/qtr)</option>}
                          </select>
                          {(billingCycles[index] === "Year" || billingCycles[index] === "Quarter") && (
                            <div className="flex items-center gap-2 text-sm text-muted-foreground">
                              <span className="px-2 py-0.5 rounded-md bg-primary/10 text-primary font-medium text-xs">
                                Save {billingCycles[index] === "Year" ? "20%" : "10%"}
                              </span>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  )}

                  <ul className="flex-grow space-y-3 mb-8">
                    {plan.features.map((feature, fIndex) => (
                      <li key={fIndex} className="flex gap-3 text-sm text-muted-foreground">
                        <Check className="h-5 w-5 text-primary shrink-0" />
                        <span>{feature}</span>
                      </li>
                    ))}
                  </ul>

                  <Button
                    onClick={() => {
                      if (plan.cta === "quote-modal") {
                        openModal(plan.name)
                      } else {
                        let role = "Student Basic";
                        let planId = "3";

                        if (plan.name === "Free" || plan.name === "Free Research") {
                          if (activeTab === "student") {
                            if (activeStudentSub !== "document-analyze") {
                              role = "Curriculum Library";
                            }
                            planId = "1";
                          } else if (activeTab === "research") {
                            role = "Research";
                            planId = "1";
                          }
                        } else if (plan.name === "Basic") {
                          role = "Student Basic";
                          planId = "3";
                        } else if (plan.name === "Research" || plan.name === "Professional") {
                          role = "Research";
                          planId = "10";
                        } else if (plan.curriculumOptions || plan.name === "Student Curriculum Library") {
                          role = "Curriculum Library";
                          if (activeStudentSub === "cbse") planId = "6";
                          else if (activeStudentSub === "mhb") planId = "7";
                          else if (activeStudentSub === "igcse") planId = "8";
                          else if (activeStudentSub === "iti") planId = "9";
                          else if (activeStudentSub === "nursing") planId = "11";
                        }

                        const isPaid = plan.cta === "buy";
                        const isLocalhost = typeof window !== 'undefined' && (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
                        const appUrl = isLocalhost ? "http://localhost:3001" : "https://app.codeframeai.com";
                        const selectedBilling = billingCycles[index] || "Month";

                        window.location.href = `${appUrl}/#/login?source=plan&role=${encodeURIComponent(role)}&isPaid=${isPaid}&planId=${planId}&billingType=${selectedBilling}`;
                      }
                    }}
                    variant={plan.highlight ? "default" : "outline"}
                    className="w-full"
                  >
                    {plan.cta === "signup" ? "Start Free Trial" : plan.cta === "buy" ? "Buy Now" : "Call for Trial & Quote"}
                  </Button>
                </div>
              )
            })}
          </div>
        </div>
      </section>

      {/* Quote Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-background/80 backdrop-blur-sm" onClick={closeModal} />
          <div className="relative w-full max-w-lg bg-card rounded-2xl border border-border shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between p-6 border-b border-border bg-muted/30">
              <h3 className="text-xl font-bold text-foreground">Request a Trial & Quote</h3>
              <button onClick={closeModal} className="p-2 rounded-lg hover:bg-muted transition-colors text-muted-foreground hover:text-foreground">
                <X className="h-5 w-5" />
              </button>
            </div>

            <form className="p-6 space-y-4 max-h-[70vh] overflow-y-auto" onSubmit={(e) => { e.preventDefault(); closeModal(); }}>
              <div className="grid gap-2">
                <label className="text-sm font-medium">Full Name *</label>
                <input required className="w-full px-4 py-2 rounded-lg border bg-background border-input" placeholder="Enter your full name" />
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium">Email Address *</label>
                <input required type="email" className="w-full px-4 py-2 rounded-lg border bg-background border-input" placeholder="name@example.com" />
              </div>
              <div className="grid sm:grid-cols-2 gap-4">
                <div className="grid gap-2">
                  <label className="text-sm font-medium">Phone Number</label>
                  <input className="w-full px-4 py-2 rounded-lg border bg-background border-input" placeholder="+91..." />
                </div>
                <div className="grid gap-2">
                  <label className="text-sm font-medium">Organization</label>
                  <input className="w-full px-4 py-2 rounded-lg border bg-background border-input" placeholder="Company/Institution" />
                </div>
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium">Interested Plan</label>
                <select className="w-full px-4 py-2 rounded-lg border bg-background border-input" defaultValue={selectedPlan}>
                  <option value="faculty">Faculty</option>
                  <option value="dept">Department Head</option>
                  <option value="market">Market Research</option>
                </select>
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium">Number of Users</label>
                <input type="number" min="1" className="w-full px-4 py-2 rounded-lg border bg-background border-input" placeholder="10" />
              </div>
              <div className="grid gap-2">
                <label className="text-sm font-medium">Additional Information</label>
                <textarea rows={4} className="w-full px-4 py-2 rounded-lg border bg-background border-input resize-none" placeholder="Tell us more about your needs..." />
              </div>

              <div className="pt-4 flex gap-3">
                <Button variant="outline" type="button" onClick={closeModal} className="flex-1">Cancel</Button>
                <Button type="submit" className="flex-1">Submit Request</Button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
