"use client";

import { useEffect } from "react";
import Link from "next/link";
import {
  ArrowRight,
  CheckCircle2,
  CreditCard,
  FileText,
  Mail,
  RefreshCw,
  TrendingUp,
  Zap,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { getArchetypeById } from "@/data/archetypes";
import { getPackageById } from "@/data/packages";
import { useAuthStore } from "@/stores/auth-store";
import { useReportStore } from "@/stores/report-store";
import { cn } from "@/lib/utils";

function getEmailTimeline(createdAt: string) {
  const created = new Date(createdAt);
  const now = new Date();
  const daysSince = Math.floor((now.getTime() - created.getTime()) / (1000 * 60 * 60 * 24));

  return [
    {
      day: 0,
      subject: "Your Novalife Report is Ready",
      preview: "Your personalised metabolic report has been unlocked and is ready to view.",
      icon: FileText,
      sent: true,
    },
    {
      day: 3,
      subject: "Check In: How Are You Getting On?",
      preview: "It's been 3 days since you received your report. Have you had a chance to read it?",
      icon: Mail,
      sent: daysSince >= 3,
    },
    {
      day: 7,
      subject: "7-Day Insight: Your Top Recommendation",
      preview: "This week, focus on one action from your report. Here's our top pick for you.",
      icon: TrendingUp,
      sent: daysSince >= 7,
    },
    {
      day: 14,
      subject: "Two Weeks In — How's Your Progress?",
      preview: "Check in on your first two weeks of implementing your personalised protocol.",
      icon: CheckCircle2,
      sent: daysSince >= 14,
    },
    {
      day: 30,
      subject: "30-Day Review: Time to Reassess",
      preview: "A full month has passed. Let's review your progress and adjust your plan.",
      icon: RefreshCw,
      sent: daysSince >= 30,
    },
  ];
}

export default function DashboardPage() {
  const { user, loadFromStorage } = useAuthStore();
  const { reports, loadReports } = useReportStore();

  useEffect(() => {
    loadFromStorage();
  }, [loadFromStorage]);

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

  if (!user) return null;

  const archetype = user.archetypeResult
    ? getArchetypeById(user.archetypeResult.primaryArchetype)
    : null;
  const pkg = user.purchasedPackage ? getPackageById(user.purchasedPackage) : null;
  const emailTimeline = getEmailTimeline(user.createdAt);
  const mostRecentReport = reports[reports.length - 1];

  return (
    <div className="space-y-6">
      {/* Welcome banner */}
      <div className="rounded-2xl bg-gradient-to-r from-teal-600 to-teal-700 p-6 text-white shadow-lg shadow-teal-600/20">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 className="text-2xl font-extrabold mb-1">
              Welcome back, {user.firstName}! 👋
            </h1>
            <p className="text-teal-100 text-sm">
              {archetype
                ? `Your ${archetype.name} profile is active.`
                : "Complete the assessment to unlock your metabolic profile."}
            </p>
          </div>
          {archetype && (
            <div className="flex-shrink-0 bg-white/15 backdrop-blur-sm rounded-xl px-4 py-2 text-sm font-semibold">
              {archetype.name}
            </div>
          )}
        </div>
      </div>

      {/* Stats row */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border border-gray-100 p-5 shadow-sm">
          <div className="flex items-center gap-3 mb-2">
            <div className="h-9 w-9 rounded-lg bg-blue-50 flex items-center justify-center">
              <FileText className="h-4.5 w-4.5 text-blue-600" style={{ width: "18px", height: "18px" }} />
            </div>
            <span className="text-sm text-gray-500 font-medium">Reports</span>
          </div>
          <p className="text-2xl font-extrabold text-gray-900">{reports.length}</p>
          <p className="text-xs text-gray-400 mt-1">
            {reports.length === 0 ? "No reports yet" : "Available to view"}
          </p>
        </div>

        <div className="bg-white rounded-xl border border-gray-100 p-5 shadow-sm">
          <div className="flex items-center gap-3 mb-2">
            <div className="h-9 w-9 rounded-lg bg-teal-50 flex items-center justify-center">
              <CreditCard className="h-4.5 w-4.5 text-teal-600" style={{ width: "18px", height: "18px" }} />
            </div>
            <span className="text-sm text-gray-500 font-medium">Package</span>
          </div>
          <p className="text-2xl font-extrabold text-gray-900">
            {pkg ? pkg.name : "Free"}
          </p>
          <p className="text-xs text-gray-400 mt-1">
            {pkg ? pkg.tagline : "No package purchased"}
          </p>
        </div>

        <div className="bg-white rounded-xl border border-gray-100 p-5 shadow-sm">
          <div className="flex items-center gap-3 mb-2">
            <div className="h-9 w-9 rounded-lg bg-green-50 flex items-center justify-center">
              <Zap className="h-4.5 w-4.5 text-green-600" style={{ width: "18px", height: "18px" }} />
            </div>
            <span className="text-sm text-gray-500 font-medium">Status</span>
          </div>
          <p className="text-2xl font-extrabold text-gray-900 capitalize">
            {user.subscriptionStatus ?? "Active"}
          </p>
          <p className="text-xs text-gray-400 mt-1">Account standing</p>
        </div>
      </div>

      {/* Main grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Archetype card */}
        {archetype ? (
          <div
            className="rounded-2xl border p-5 shadow-sm"
            style={{ backgroundColor: `${archetype.color}0D`, borderColor: `${archetype.color}25` }}
          >
            <p
              className="text-xs font-bold uppercase tracking-wider mb-2"
              style={{ color: archetype.color }}
            >
              Your Metabolic Archetype
            </p>
            <h2 className="text-xl font-extrabold text-gray-900 mb-1">{archetype.name}</h2>
            <p className="text-sm text-gray-600 mb-4">{archetype.tagline}</p>
            <div className="flex flex-wrap gap-1.5">
              {archetype.traits.slice(0, 3).map((trait, i) => (
                <span
                  key={i}
                  className="text-xs px-2.5 py-1 rounded-full text-white font-medium"
                  style={{ backgroundColor: archetype.color }}
                >
                  {trait.split(" ").slice(0, 4).join(" ")}…
                </span>
              ))}
            </div>
          </div>
        ) : (
          <div className="rounded-2xl border border-dashed border-gray-200 p-5 flex flex-col items-center justify-center text-center gap-3 bg-gray-50">
            <div className="h-12 w-12 rounded-full bg-gray-100 flex items-center justify-center">
              <Zap className="h-6 w-6 text-gray-400" />
            </div>
            <div>
              <p className="font-semibold text-gray-700 mb-1">No Assessment Yet</p>
              <p className="text-sm text-gray-400">
                Take the quiz to discover your metabolic archetype
              </p>
            </div>
            <Link href="/quiz">
              <Button size="sm" className="bg-teal-600 hover:bg-teal-700 text-white rounded-lg">
                Take Assessment
              </Button>
            </Link>
          </div>
        )}

        {/* Quick actions */}
        <div className="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm">
          <h2 className="text-sm font-bold text-gray-700 uppercase tracking-wider mb-4">
            Quick Actions
          </h2>
          <div className="space-y-2">
            {mostRecentReport ? (
              <Link href={`/dashboard/reports/${mostRecentReport.id}`}>
                <button className="w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-teal-50 hover:bg-teal-100 transition-colors group">
                  <FileText className="h-4.5 w-4.5 text-teal-600 flex-shrink-0" style={{ width: "18px", height: "18px" }} />
                  <span className="text-sm font-medium text-gray-700 flex-1 text-left">View My Report</span>
                  <ArrowRight className="h-4 w-4 text-teal-600 group-hover:translate-x-0.5 transition-transform" />
                </button>
              </Link>
            ) : (
              <Link href="/result/unlock">
                <button className="w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-teal-50 hover:bg-teal-100 transition-colors group">
                  <FileText className="h-4.5 w-4.5 text-teal-600 flex-shrink-0" style={{ width: "18px", height: "18px" }} />
                  <span className="text-sm font-medium text-gray-700 flex-1 text-left">Unlock Report</span>
                  <ArrowRight className="h-4 w-4 text-teal-600 group-hover:translate-x-0.5 transition-transform" />
                </button>
              </Link>
            )}

            {(!pkg || pkg.id !== "professional") && (
              <Link href="/dashboard/subscription">
                <button className="w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-amber-50 hover:bg-amber-100 transition-colors group">
                  <CreditCard className="h-4.5 w-4.5 text-amber-600 flex-shrink-0" style={{ width: "18px", height: "18px" }} />
                  <span className="text-sm font-medium text-gray-700 flex-1 text-left">Upgrade Plan</span>
                  <ArrowRight className="h-4 w-4 text-amber-600 group-hover:translate-x-0.5 transition-transform" />
                </button>
              </Link>
            )}

            <Link href="/quiz">
              <button className="w-full flex items-center gap-3 px-4 py-3 rounded-xl bg-gray-50 hover:bg-gray-100 transition-colors group">
                <RefreshCw className="h-4.5 w-4.5 text-gray-500 flex-shrink-0" style={{ width: "18px", height: "18px" }} />
                <span className="text-sm font-medium text-gray-700 flex-1 text-left">Re-take Assessment</span>
                <ArrowRight className="h-4 w-4 text-gray-400 group-hover:translate-x-0.5 transition-transform" />
              </button>
            </Link>
          </div>
        </div>
      </div>

      {/* Email timeline */}
      {emailTimeline.length > 0 && (
        <div className="bg-white rounded-2xl border border-gray-100 p-6 shadow-sm">
          <div className="flex items-center gap-2 mb-5">
            <Mail className="h-5 w-5 text-teal-600" />
            <h2 className="text-base font-bold text-gray-900">Simulated Email Timeline</h2>
          </div>
          <p className="text-xs text-gray-400 mb-5">
            These are the automated emails Novalife would send to support your health journey.
          </p>

          <div className="relative">
            {/* Timeline line */}
            <div className="absolute left-5 top-5 bottom-5 w-px bg-gray-100" />

            <div className="space-y-4">
              {emailTimeline.map((email) => {
                const Icon = email.icon;
                return (
                  <div key={email.day} className="flex items-start gap-4 pl-1">
                    {/* Status dot */}
                    <div
                      className={cn(
                        "relative z-10 flex h-10 w-10 items-center justify-center rounded-full flex-shrink-0 border-2",
                        email.sent
                          ? "bg-teal-600 border-teal-600"
                          : "bg-white border-gray-200",
                      )}
                    >
                      <Icon
                        className={cn("h-4 w-4", email.sent ? "text-white" : "text-gray-400")}
                      />
                    </div>

                    <div className="flex-1 min-w-0 pb-4">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-xs font-semibold text-gray-400 uppercase">
                          Day {email.day}
                        </span>
                        <span
                          className={cn(
                            "text-xs font-bold px-2 py-0.5 rounded-full",
                            email.sent
                              ? "bg-green-100 text-green-700"
                              : "bg-gray-100 text-gray-500",
                          )}
                        >
                          {email.sent ? "Sent" : "Upcoming"}
                        </span>
                      </div>
                      <p className="text-sm font-semibold text-gray-800 mt-0.5">{email.subject}</p>
                      <p className="text-xs text-gray-400 mt-0.5 leading-relaxed">
                        {email.preview}
                      </p>
                      {email.sent && (
                        <button
                          className="mt-2 text-xs text-teal-600 hover:text-teal-700 font-semibold inline-flex items-center gap-1"
                          onClick={() => {
                            /* preview modal — future enhancement */
                          }}
                        >
                          Preview email
                          <ArrowRight className="h-3 w-3" />
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
