"use client";

import { useEffect } from "react";

import Link from "next/link";

import { ArrowRight, CreditCard } from "lucide-react";
import { toast } from "sonner";

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { PACKAGES } from "@/data/packages";
import { useAuthStore } from "@/stores/auth-store";
import { useSubscriptionStore } from "@/stores/subscription-store";

const STATUS_COLORS: Record<string, string> = {
  succeeded: "bg-green-100 text-green-700",
  failed: "bg-red-100 text-red-700",
  refunded: "bg-amber-100 text-amber-700",
};

export default function SubscriptionPage() {
  const user = useAuthStore((s) => s.user);
  const { subscription, billingHistory, loadSubscription, cancelSubscription } = useSubscriptionStore();

  useEffect(() => {
    if (user?.id) loadSubscription(user.id);
  }, [user?.id, loadSubscription]);

  const currentPackage = user?.purchasedPackage ? PACKAGES.find((p) => p.id === user.purchasedPackage) : null;
  const nextPackage = !currentPackage ? PACKAGES[0] : currentPackage.id === "starter" ? PACKAGES[1] : currentPackage.id === "advanced" ? PACKAGES[2] : null;

  const handleCancel = () => {
    cancelSubscription();
    toast.success("Subscription cancelled. You retain access until the end of the billing period.");
  };

  return (
    <div className="space-y-6 p-6 max-w-2xl">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Subscription & Billing</h1>
        <p className="text-sm text-gray-500 mt-1">Manage your plan and billing history.</p>
      </div>

      {/* Current Plan */}
      <Card className="border-gray-100">
        <CardHeader className="pb-3"><CardTitle className="text-base">Current Plan</CardTitle></CardHeader>
        <CardContent>
          {currentPackage ? (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xl font-bold text-gray-900 capitalize">{currentPackage.name}</p>
                  <p className="text-sm text-gray-500">{currentPackage.tagline}</p>
                </div>
                <div className="text-right">
                  <p className="text-2xl font-bold text-teal-600">CHF {currentPackage.priceChf}</p>
                  <p className="text-xs text-gray-400">{currentPackage.billingLabel}</p>
                </div>
              </div>
              {subscription && (
                <div className="rounded-xl bg-gray-50 p-4 text-sm space-y-2">
                  <div className="flex justify-between">
                    <span className="text-gray-500">Status</span>
                    <Badge className={subscription.status === "active" ? "bg-green-100 text-green-700 border-0" : "bg-gray-100 text-gray-700 border-0"}>
                      {subscription.status}
                    </Badge>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500">Started</span>
                    <span className="font-medium">{subscription.startDate}</span>
                  </div>
                  {subscription.nextBillingDate && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">Next billing</span>
                      <span className="font-medium">{subscription.nextBillingDate}</span>
                    </div>
                  )}
                </div>
              )}
              {subscription?.status === "active" && (
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="outline" className="text-red-600 border-red-200 hover:bg-red-50">Cancel Subscription</Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>Cancel your subscription?</AlertDialogTitle>
                      <AlertDialogDescription>
                        You will retain access to your Professional benefits until the end of your current billing period. After that, you will revert to your purchased report tier.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>Keep Subscription</AlertDialogCancel>
                      <AlertDialogAction className="bg-red-600 hover:bg-red-700 text-white" onClick={handleCancel}>
                        Yes, Cancel
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              )}
            </div>
          ) : (
            <div className="text-center py-4">
              <CreditCard className="h-10 w-10 text-gray-300 mx-auto mb-3" />
              <p className="text-gray-500 text-sm">No active package</p>
              <Button asChild size="sm" className="mt-3 bg-teal-600 hover:bg-teal-700 text-white">
                <Link href="/result/unlock">Get Your Report</Link>
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Upgrade CTA */}
      {nextPackage && (
        <div className="rounded-xl border border-teal-100 bg-teal-50 p-5 flex items-center justify-between gap-4">
          <div>
            <p className="font-semibold text-teal-900">Upgrade to {nextPackage.name}</p>
            <p className="text-sm text-teal-700 mt-0.5">{nextPackage.tagline}</p>
          </div>
          <Button asChild size="sm" className="shrink-0 bg-teal-600 hover:bg-teal-700 text-white">
            <Link href="/result/unlock">
              Upgrade <ArrowRight className="ml-1 h-3 w-3" />
            </Link>
          </Button>
        </div>
      )}

      {/* Billing History */}
      <Card className="border-gray-100">
        <CardHeader className="pb-3"><CardTitle className="text-base">Billing History</CardTitle></CardHeader>
        <CardContent className="p-0">
          {billingHistory.length === 0 ? (
            <p className="text-center text-sm text-gray-400 py-6">No billing history yet.</p>
          ) : (
            <div className="divide-y divide-gray-50">
              {billingHistory.map((txn) => (
                <div key={txn.id} className="flex items-center justify-between px-5 py-3">
                  <div>
                    <p className="text-sm font-medium text-gray-900">{txn.description}</p>
                    <p className="text-xs text-gray-400">{new Date(txn.createdAt).toLocaleDateString("en-GB", { year: "numeric", month: "long", day: "numeric" })}</p>
                  </div>
                  <div className="text-right">
                    <p className="font-semibold text-gray-900">CHF {txn.amount}</p>
                    <Badge className={STATUS_COLORS[txn.status] + " border-0 text-xs capitalize mt-0.5"}>
                      {txn.status}
                    </Badge>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Separator />
      <p className="text-xs text-gray-400 text-center">
        For billing issues, contact support@novalife.com · All prices in CHF
      </p>
    </div>
  );
}
