"use client";

import { useAuth } from "@/lib/auth-context";
import {
  getGuideById,
  getBlogsByGuide,
  mockReports,
  mockIDCardRequests,
  mockCertifications,
} from "@/lib/mock-data";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DashboardBreadcrumb } from "@/components/dashboard/dashboard-breadcrumb";
import Link from "next/link";
import {
  BookOpen,
  FileText,
  CreditCard,
  Award,
  TrendingUp,
  Users,
  ArrowRight,
  Calendar,
  CheckCircle2,
  Clock,
  AlertCircle,
} from "lucide-react";

export default function DashboardPage() {
  const { user } = useAuth();
  const guide = user?.guideId ? getGuideById(user.guideId) : null;

  const blogs = user?.guideId ? getBlogsByGuide(user.guideId) : [];
  const reports = mockReports.filter((r) => r.guideId === user?.guideId);
  const idCardRequest = mockIDCardRequests.find(
    (r) => r.guideId === user?.guideId,
  );
  const certifications = guide?.certifications || [];
  const idCardRejectReason =
    idCardRequest?.rejectReason || idCardRequest?.reject_reason || "";
  const pendingCerts = mockCertifications.filter(
    (c) => c.guideId === user?.guideId && c.status === "pending",
  );

  const publishedBlogs = blogs.filter((b) => b.status === "published").length;
  const pendingBlogs = blogs.filter((b) => b.status === "pending").length;
  const totalTours = reports.reduce((acc, r) => acc + r.toursCount, 0);
  const totalTourists = reports.reduce((acc, r) => acc + r.touristsServed, 0);

  const stats = [
    {
      label: "Published Blogs",
      value: publishedBlogs,
      icon: BookOpen,
      href: "/dashboard/blogs",
    },
    {
      label: "Tours Conducted",
      value: totalTours,
      icon: TrendingUp,
      href: "/dashboard/reports",
    },
    {
      label: "Tourists Served",
      value: totalTourists,
      icon: Users,
      href: "/dashboard/reports",
    },
    {
      label: "Certifications",
      value: certifications.filter((c) => c.status === "approved").length,
      icon: Award,
      href: "/dashboard/certifications",
    },
  ];

  const quickActions = [
    { label: "Write New Blog", href: "/dashboard/blogs/new", icon: BookOpen },
    {
      label: "Submit Monthly Report",
      href: "/dashboard/reports/new",
      icon: FileText,
    },
    { label: "Request ID Card", href: "/dashboard/id-card", icon: CreditCard },
    {
      label: "Apply for Certification",
      href: "/dashboard/certifications",
      icon: Award,
    },
  ];

  return (
    <div className="space-y-5">
      <DashboardBreadcrumb current="Overview" />

      {/* Header */}
      <div className="flex flex-col gap-4 rounded-3xl border border-[var(--theme-border)] bg-white p-5 shadow-sm sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-black text-foreground">
            Welcome back, {user?.name?.split(" ")[0]}!
          </h1>
          <p className="mt-1 text-sm font-medium text-muted-foreground">
            Here&apos;s an overview of your guide activities
          </p>
        </div>
        <Button
          asChild
          className="rounded-full bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] px-6 font-black text-white shadow-lg shadow-[var(--theme-secondary)]/25 hover:from-[var(--theme-primary)] hover:to-[var(--theme-primary-dark)]"
        >
          <Link href="/dashboard/id-card">
            <CreditCard className="mr-2 h-4 w-4" />
            Get My ID Card
          </Link>
        </Button>
      </div>

      {/* Status Banner */}
      {guide && (
        <Card
          className={
            guide.status === "verified"
              ? "rounded-3xl border-green-200 bg-green-50 py-0 shadow-sm"
              : "rounded-3xl border-yellow-200 bg-yellow-50 py-0 shadow-sm"
          }
        >
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              {guide.status === "verified" ? (
                <>
                  <CheckCircle2 className="h-5 w-5 text-accent" />
                  <div>
                    <p className="font-black text-foreground">
                      Your profile is verified
                    </p>
                    <p className="text-sm text-muted-foreground">
                      Your guide profile is visible to tourists
                    </p>
                  </div>
                </>
              ) : (
                <>
                  <Clock className="h-5 w-5 text-yellow-600" />
                  <div>
                    <p className="font-black text-foreground">
                      Verification pending
                    </p>
                    <p className="text-sm text-muted-foreground">
                      Your profile is under review by the tourism department
                    </p>
                  </div>
                </>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Stats Grid */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {stats.map((stat) => (
          <Link key={stat.label} href={stat.href}>
            <Card className="group cursor-pointer overflow-hidden rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm transition-all hover:-translate-y-1 hover:shadow-xl hover:shadow-[var(--theme-secondary)]/10">
              <CardContent className="p-5">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-semibold text-muted-foreground">
                      {stat.label}
                    </p>
                    <p className="mt-3 text-3xl font-black text-foreground">
                      {stat.value}
                    </p>
                  </div>
                  <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--theme-surface-strong)] text-[var(--theme-primary)] transition-transform group-hover:scale-110">
                    <stat.icon className="h-6 w-6" />
                  </div>
                </div>
              </CardContent>
            </Card>
          </Link>
        ))}
      </div>

      {/* Quick Actions & Notifications */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Quick Actions */}
        <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
          <CardHeader className="px-5 pt-5">
            <CardTitle className="flex items-center gap-2 text-xl font-black">
              <Clock className="h-5 w-5 text-[var(--theme-primary)]" />
              Quick Actions
            </CardTitle>
            <CardDescription>Common tasks you can perform</CardDescription>
          </CardHeader>
          <CardContent className="p-5 pt-2">
            <div className="grid gap-3 sm:grid-cols-2">
              {quickActions.map((action) => (
                <Link key={action.label} href={action.href}>
                  <div className="group flex items-center justify-between rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-4 shadow-sm transition-all hover:-translate-y-0.5 hover:border-[var(--theme-secondary)]/35 hover:shadow-lg hover:shadow-[var(--theme-secondary)]/10">
                    <div className="flex min-w-0 items-center gap-3">
                      <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--theme-surface-strong)] text-[var(--theme-primary)]">
                        <action.icon className="h-5 w-5" />
                      </span>
                      <span className="truncate text-sm font-black text-foreground">
                        {action.label}
                      </span>
                    </div>
                    <ArrowRight className="h-4 w-4 shrink-0 text-[var(--theme-primary)] transition-transform group-hover:translate-x-0.5" />
                  </div>
                </Link>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Notifications / Pending Items */}
        <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
          <CardHeader className="px-5 pt-5">
            <CardTitle className="text-xl font-black">Pending Items</CardTitle>
            <CardDescription>Items requiring your attention</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4 p-5 pt-2">
            {pendingBlogs > 0 && (
              <div className="flex items-center justify-between rounded-2xl bg-[var(--theme-surface-soft)] p-3">
                <div className="flex items-center gap-3">
                  <Clock className="h-5 w-5 text-yellow-600" />
                  <div>
                    <p className="text-sm font-medium text-foreground">
                      {pendingBlogs} blog(s) pending approval
                    </p>
                    <p className="text-xs text-muted-foreground">
                      Awaiting admin review
                    </p>
                  </div>
                </div>
                <Link href="/dashboard/blogs">
                  <Button size="sm" variant="ghost">
                    View
                    <ArrowRight className="h-4 w-4 ml-1" />
                  </Button>
                </Link>
              </div>
            )}

            {idCardRequest && idCardRequest.status === "pending" && (
              <div className="flex items-center justify-between rounded-2xl bg-[var(--theme-surface-soft)] p-3">
                <div className="flex items-center gap-3">
                  <CreditCard className="h-5 w-5 text-blue-600" />
                  <div>
                    <p className="text-sm font-medium text-foreground">
                      ID Card request pending
                    </p>
                    <p className="text-xs text-muted-foreground">
                      Submitted on{" "}
                      {new Date(idCardRequest.requestedAt).toLocaleDateString()}
                    </p>
                  </div>
                </div>
                <Badge variant="secondary">Pending</Badge>
              </div>
            )}

            {idCardRequest && idCardRequest.status === "rejected" && (
              <div className="flex items-center justify-between gap-3 rounded-2xl bg-red-50 p-3 text-red-700">
                <div className="flex min-w-0 items-start gap-3">
                  <AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-red-600" />
                  <div className="min-w-0">
                    <p className="text-sm font-bold text-red-700">
                      ID Card request rejected
                    </p>
                    <p className="mt-1 break-words text-xs font-medium text-red-700">
                      {idCardRejectReason ||
                        "Please review your ID card details and submit again."}
                    </p>
                  </div>
                </div>
                <Button
                  asChild
                  size="sm"
                  variant="ghost"
                  className="shrink-0 text-red-700 hover:bg-red-100 hover:text-red-800"
                >
                  <Link href="/dashboard/id-card">
                    View
                    <ArrowRight className="ml-1 h-4 w-4" />
                  </Link>
                </Button>
              </div>
            )}

            {pendingCerts.length > 0 && (
              <div className="flex items-center justify-between rounded-2xl bg-[var(--theme-surface-soft)] p-3">
                <div className="flex items-center gap-3">
                  <Award className="h-5 w-5 text-accent" />
                  <div>
                    <p className="text-sm font-medium text-foreground">
                      {pendingCerts.length} certification(s) pending
                    </p>
                    <p className="text-xs text-muted-foreground">
                      Under review
                    </p>
                  </div>
                </div>
                <Link href="/dashboard/certifications">
                  <Button size="sm" variant="ghost">
                    View
                    <ArrowRight className="h-4 w-4 ml-1" />
                  </Button>
                </Link>
              </div>
            )}

            {pendingBlogs === 0 &&
              (!idCardRequest ||
                !["pending", "rejected"].includes(idCardRequest.status)) &&
              pendingCerts.length === 0 && (
                <div className="flex items-center justify-center p-6 text-muted-foreground">
                  <div className="text-center">
                    <CheckCircle2 className="h-8 w-8 mx-auto mb-2 text-accent" />
                    <p className="text-sm">All caught up!</p>
                  </div>
                </div>
              )}
          </CardContent>
        </Card>
      </div>

      {/* Recent Activity */}
      <Card className="rounded-3xl border-[var(--theme-border)] bg-white py-0 shadow-sm">
        <CardHeader className="px-5 pt-5">
          <CardTitle className="text-xl font-black">
            Recent Blog Posts
          </CardTitle>
          <CardDescription>Your latest published content</CardDescription>
        </CardHeader>
        <CardContent className="p-5 pt-2">
          {blogs.length > 0 ? (
            <div className="space-y-4">
              {blogs.slice(0, 3).map((blog) => (
                <div
                  key={blog.id}
                  className="flex items-center justify-between rounded-2xl border border-[var(--theme-border)] bg-[var(--theme-surface-soft)] p-3"
                >
                  <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-[var(--theme-surface-strong)]">
                      <BookOpen className="h-5 w-5 text-[var(--theme-primary)]" />
                    </div>
                    <div>
                      <p className="font-medium text-foreground">
                        {blog.title}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {blog.publishedAt
                          ? new Date(blog.publishedAt).toLocaleDateString()
                          : "Draft"}
                      </p>
                    </div>
                  </div>
                  <Badge
                    variant={
                      blog.status === "published"
                        ? "default"
                        : blog.status === "pending"
                          ? "secondary"
                          : "outline"
                    }
                  >
                    {blog.status}
                  </Badge>
                </div>
              ))}
              <Link href="/dashboard/blogs">
                <Button variant="outline" className="w-full gap-2">
                  View All Blogs
                  <ArrowRight className="h-4 w-4" />
                </Button>
              </Link>
            </div>
          ) : (
            <div className="text-center py-8">
              <BookOpen className="h-12 w-12 mx-auto mb-3 text-muted-foreground" />
              <p className="text-muted-foreground mb-4">No blog posts yet</p>
              <Link href="/dashboard/blogs/new">
                <Button>Write Your First Blog</Button>
              </Link>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
