"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Save, Zap, Check, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { PLAN_LIMITS, getPlanBadgeColor } from "@/lib/plan-limits";
import { formatCurrency } from "@/lib/utils";
import Link from "next/link";
import { userApi, type UserResponse, type Plan, type PlanLimitsResponse } from "@/lib/api";
import { getValidToken } from "@/lib/auth-store";

export default function AccountPage() {
  const router = useRouter();
  const [user, setUser] = useState<UserResponse | null>(null);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [saving, setSaving] = useState(false);
  const [saveMsg, setSaveMsg] = useState("");
  const [limits, setLimits] = useState<PlanLimitsResponse | null>(null);

  useEffect(() => {
    (async () => {
      const token = await getValidToken();
      if (!token) { router.push("/login"); return; }
      try {
        const [u, planLimits] = await Promise.all([
          userApi.getMe(token),
          userApi.getLimits(token),
        ]);
        setUser(u);
        setLimits(planLimits);
        setName(u.name);
        setEmail(u.email);
      } catch {
        router.push("/login");
      }
    })();
  }, [router]);

  const handleSave = async () => {
    const token = await getValidToken();
    if (!token) return;
    setSaving(true);
    setSaveMsg("");
    try {
      const updated = await userApi.updateMe(token, { name, email });
      setUser(updated);
      setSaveMsg("Saved!");
      setTimeout(() => setSaveMsg(""), 3000);
    } catch (err: unknown) {
      setSaveMsg(err instanceof Error ? err.message : "Save failed");
    } finally {
      setSaving(false);
    }
  };

  const userPlan = (user?.plan ?? "free") as Plan;
  const planKey = userPlan in PLAN_LIMITS ? userPlan : "free";
  const videosPerDay = limits?.videos_per_day ?? PLAN_LIMITS[planKey].videos_per_day;
  const maxDurationMinutes = limits?.max_duration_minutes ?? PLAN_LIMITS[planKey].max_duration_minutes;
  const transcriptEnabled = limits?.download_transcript ?? PLAN_LIMITS[planKey].download_transcript;
  const avatarLetter = name ? name[0].toUpperCase() : "?";

  return (
    <div className="max-w-2xl">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-white">Account & Billing</h1>
        <p className="text-zinc-500 text-sm mt-1">Manage your profile and subscription</p>
      </div>

      {/* Profile */}
      <div className="glass-card p-6 mb-6">
        <h2 className="text-base font-semibold text-white mb-5">Profile</h2>
        {!user ? (
          <div className="flex items-center gap-2 text-zinc-500 text-sm py-4">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading...
          </div>
        ) : (
          <div className="space-y-4">
            <div className="flex items-center gap-4 mb-5">
              <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-violet-600 to-cyan-500 flex items-center justify-center text-2xl font-bold text-white">
                {avatarLetter}
              </div>
              <div>
                <div className="text-sm font-semibold text-white">{user.name}</div>
                <div className="text-xs text-zinc-500">{user.email}</div>
              </div>
            </div>

            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-400">Full Name</Label>
                <Input
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="bg-white/5 border-white/10 text-white h-9"
                />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-400">Email</Label>
                <Input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="bg-white/5 border-white/10 text-white h-9"
                />
              </div>
            </div>

            <div className="flex items-center gap-3">
              <Button
                size="sm"
                className="bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0"
                onClick={handleSave}
                disabled={saving}
              >
                {saving ? <Loader2 className="w-3.5 h-3.5 animate-spin mr-2" /> : <Save className="w-3.5 h-3.5 mr-2" />}
                Save Changes
              </Button>
              {saveMsg && (
                <span className={`text-xs ${saveMsg === "Saved!" ? "text-emerald-400" : "text-red-400"}`}>
                  {saveMsg}
                </span>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Current Plan */}
      <div className="glass-card p-6 mb-6">
        <h2 className="text-base font-semibold text-white mb-5">Current Plan</h2>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <Badge className={`text-sm px-3 py-1 ${getPlanBadgeColor(planKey)}`}>
              {PLAN_LIMITS[planKey].name}
            </Badge>
            <span className="text-zinc-400 text-sm">
              {PLAN_LIMITS[planKey].price_monthly === 0
                ? "Free forever"
                : formatCurrency(PLAN_LIMITS[planKey].price_monthly) + "/month"}
            </span>
          </div>
        </div>

        <div className="space-y-2 mb-5">
          {[
            `${videosPerDay >= 9999 || videosPerDay === Infinity ? "Unlimited" : videosPerDay} video${videosPerDay === 1 ? "" : "s"} per day`,
            `Max ${maxDurationMinutes >= 9999 || maxDurationMinutes === Infinity ? "unlimited" : maxDurationMinutes} minutes per video`,
            PLAN_LIMITS[planKey].watermark ? "Watermarked export" : "No watermark",
            transcriptEnabled ? "Transcript download" : "No transcript download",
          ].map((f, i) => (
            <div key={i} className="flex items-center gap-2 text-sm text-zinc-400">
              <Check className="w-3.5 h-3.5 text-zinc-600" />
              {f}
            </div>
          ))}
        </div>

        {planKey === "free" && (
          <div className="p-4 rounded-xl bg-violet-500/5 border border-violet-500/20">
            <p className="text-sm text-zinc-300 mb-3">
              Upgrade to <strong className="text-violet-300">Pro</strong> for 5 videos/day, 20-min
              limit, no watermark, and transcript export.
            </p>
            <Link href="/pricing">
              <Button
                size="sm"
                className="bg-gradient-to-r from-violet-600 to-violet-500 text-white border-0"
              >
                <Zap className="w-3.5 h-3.5 mr-1.5" />
                Upgrade to Pro — ₹799/mo
              </Button>
            </Link>
          </div>
        )}
      </div>

      {/* Billing History */}
      <div className="glass-card p-6">
        <h2 className="text-base font-semibold text-white mb-5">Billing History</h2>
        <p className="text-sm text-zinc-500">No billing history yet.</p>
      </div>

      <Separator className="my-8 bg-white/8" />

      {/* Danger Zone */}
      <div className="glass-card p-6 border border-red-500/20">
        <h2 className="text-base font-semibold text-red-400 mb-3">Danger Zone</h2>
        <p className="text-xs text-zinc-500 mb-4">
          Deleting your account permanently removes all data including job history and results.
          This cannot be undone.
        </p>
        <Button
          size="sm"
          variant="outline"
          className="border-red-500/40 text-red-400 hover:bg-red-500/10 hover:text-red-300"
        >
          Delete Account
        </Button>
      </div>
    </div>
  );
}
