import { useState } from "react";
import { motion } from "framer-motion";
import { Check, CreditCard, Users, TrendingUp, ArrowUpRight } from "lucide-react";
import { MOCK_SUBSCRIPTION_PLANS, MOCK_BILLING_HISTORY, CURRENT_SUBSCRIPTION } from "@/data/mockData";

export default function BillingPage() {
  const [currentPlanId, setCurrentPlanId] = useState(CURRENT_SUBSCRIPTION.planId);
  const [activeUsers] = useState(CURRENT_SUBSCRIPTION.activeUsers);
  const [maxUsers] = useState(CURRENT_SUBSCRIPTION.maxUsers);
  const [toast, setToast] = useState("");

  const currentPlan = MOCK_SUBSCRIPTION_PLANS.find(p => p.id === currentPlanId)!;
  const usagePercent = Math.min(100, Math.round((activeUsers / maxUsers) * 100));

  const handleUpgrade = (planId: number) => {
    setCurrentPlanId(planId);
    const plan = MOCK_SUBSCRIPTION_PLANS.find(p => p.id === planId)!;
    setToast(`Switched to ${plan.name} plan`);
    setTimeout(() => setToast(""), 3000);
  };

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Billing & Subscription</h1>
        <p className="text-sm text-muted-foreground mt-1">Manage your plan and billing details</p>
      </div>

      {toast && (
        <div className="fixed top-4 right-4 z-50 bg-emerald-600 text-white px-4 py-2.5 rounded-lg text-sm font-medium shadow-lg">
          {toast}
        </div>
      )}

      {/* Current plan summary */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }}
          className="bg-card border border-card-border rounded-xl p-5 shadow-sm"
        >
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-blue-50 text-blue-600 rounded-lg"><CreditCard className="w-5 h-5" /></div>
            <div>
              <p className="text-xs text-muted-foreground">Current Plan</p>
              <p className="font-bold text-foreground text-lg">{currentPlan.name}</p>
            </div>
          </div>
          <p className="text-2xl font-bold text-blue-600">${currentPlan.pricePerMonth}<span className="text-sm font-normal text-muted-foreground">/mo</span></p>
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }}
          className="bg-card border border-card-border rounded-xl p-5 shadow-sm"
        >
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-emerald-50 text-emerald-600 rounded-lg"><Users className="w-5 h-5" /></div>
            <div>
              <p className="text-xs text-muted-foreground">User Seats</p>
              <p className="font-bold text-foreground text-lg">{activeUsers} / {currentPlan.maxUsers}</p>
            </div>
          </div>
          <div className="h-2 bg-muted rounded-full overflow-hidden">
            <div className={`h-full rounded-full transition-all duration-700 ${usagePercent >= 90 ? "bg-rose-500" : usagePercent >= 70 ? "bg-amber-500" : "bg-emerald-500"}`}
              style={{ width: `${usagePercent}%` }} />
          </div>
          <p className="text-xs text-muted-foreground mt-1">{usagePercent}% used</p>
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}
          className="bg-card border border-card-border rounded-xl p-5 shadow-sm"
        >
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-indigo-50 text-indigo-600 rounded-lg"><TrendingUp className="w-5 h-5" /></div>
            <div>
              <p className="text-xs text-muted-foreground">Next billing</p>
              <p className="font-bold text-foreground text-lg">May 1, 2025</p>
            </div>
          </div>
          <p className="text-sm text-muted-foreground">Period: Apr 1 — May 1, 2025</p>
          <span className="inline-flex mt-2 px-2 py-0.5 bg-emerald-100 text-emerald-800 text-xs font-medium rounded-full">Active</span>
        </motion.div>
      </div>

      {/* Plan comparison */}
      <div>
        <h2 className="text-base font-semibold text-foreground mb-4">Available Plans</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
          {MOCK_SUBSCRIPTION_PLANS.map((plan, i) => {
            const isCurrent = plan.id === currentPlanId;
            return (
              <motion.div
                key={plan.id}
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.1 }}
                className={`relative bg-card border rounded-xl p-6 shadow-sm transition-all ${isCurrent ? "border-blue-500 ring-2 ring-blue-200" : plan.popular ? "border-blue-200" : "border-card-border"}`}
              >
                {plan.popular && (
                  <div className="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-0.5 bg-blue-600 text-white text-xs font-semibold rounded-full">
                    Most Popular
                  </div>
                )}
                {isCurrent && (
                  <div className="absolute -top-3 right-4 px-3 py-0.5 bg-emerald-600 text-white text-xs font-semibold rounded-full">
                    Current
                  </div>
                )}
                <h3 className="font-bold text-foreground text-lg">{plan.name}</h3>
                <p className="text-xs text-muted-foreground mt-1 mb-4">{plan.description}</p>
                <p className="text-3xl font-bold text-foreground mb-1">
                  {plan.pricePerMonth === 0 ? "Free" : `$${plan.pricePerMonth}`}
                  {plan.pricePerMonth > 0 && <span className="text-base font-normal text-muted-foreground">/month</span>}
                </p>
                <p className="text-xs text-muted-foreground mb-5">
                  {plan.maxUsers >= 999 ? "Unlimited users" : `Up to ${plan.maxUsers} users`}
                </p>
                <ul className="space-y-2 mb-6">
                  {plan.features.map(f => (
                    <li key={f} className="flex items-start gap-2 text-xs text-foreground">
                      <Check className="w-3.5 h-3.5 text-emerald-500 mt-0.5 flex-shrink-0" />
                      {f}
                    </li>
                  ))}
                </ul>
                <button
                  onClick={() => !isCurrent && handleUpgrade(plan.id)}
                  disabled={isCurrent}
                  className={`w-full py-2.5 rounded-lg text-sm font-medium transition flex items-center justify-center gap-1.5 ${
                    isCurrent
                      ? "bg-muted text-muted-foreground cursor-default"
                      : plan.popular
                        ? "bg-blue-600 text-white hover:bg-blue-700"
                        : "bg-card border border-border text-foreground hover:bg-muted"
                  }`}
                >
                  {isCurrent ? "Current Plan" : plan.id > currentPlanId ? <><ArrowUpRight className="w-3.5 h-3.5" /> Upgrade</> : "Downgrade"}
                </button>
              </motion.div>
            );
          })}
        </div>
      </div>

      {/* Billing history */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.4 }}
        className="bg-card border border-card-border rounded-xl shadow-sm overflow-hidden"
      >
        <div className="px-6 py-4 border-b border-border">
          <h2 className="text-sm font-semibold text-foreground">Billing History</h2>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border bg-muted/30">
              <th className="text-left px-5 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Date</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Description</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Plan</th>
              <th className="text-right px-5 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Amount</th>
              <th className="text-right px-5 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Status</th>
            </tr>
          </thead>
          <tbody>
            {MOCK_BILLING_HISTORY.map((record, i) => (
              <tr key={record.id} className={i < MOCK_BILLING_HISTORY.length - 1 ? "border-b border-border/50" : ""}>
                <td className="px-5 py-3.5 text-muted-foreground">{record.billingDate}</td>
                <td className="px-4 py-3.5 text-foreground">{record.description}</td>
                <td className="px-4 py-3.5">
                  <span className="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded font-medium">{record.planName}</span>
                </td>
                <td className="px-5 py-3.5 text-right font-semibold text-foreground">
                  {record.amount === 0 ? "Free" : `$${record.amount}`}
                </td>
                <td className="px-5 py-3.5 text-right">
                  <span className="inline-flex px-2 py-0.5 bg-emerald-100 text-emerald-800 text-xs font-medium rounded-full capitalize">{record.status}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </motion.div>
    </div>
  );
}
