"use client";

import Link from "next/link";
import {
  Home,
  CheckSquare,
  HardHat,
  FileText,
  MapPin,
  ArrowRight,
  Plus,
  CalendarClock,
  Sparkles,
  CircleAlert,
} from "lucide-react";
import { useResidences } from "@/lib/hooks/use-residences";
import { useTasks } from "@/lib/hooks/use-tasks";
import { useAuthStore } from "@/stores/auth";
import { useDataProvider } from "@/lib/demo/data-provider-context";
import { Button } from "@/components/ui/button";
import { TemplateSuggestions } from "@/components/dashboard/template-suggestions";
import { Skeleton } from "@/components/ui/skeleton";
import type { MyResidenceResponse } from "@/lib/api/residences";
import type { TaskResponse } from "@/lib/api/tasks";

/* ─── Helpers ─── */

function getTimeGreeting() {
  const h = new Date().getHours();
  if (h < 12) return "Good morning";
  if (h < 17) return "Good afternoon";
  return "Good evening";
}

function getRelativeDate(dateStr: string) {
  const date = new Date(dateStr);
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const target = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  const diff = Math.round((target.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));

  if (diff < 0) return "Overdue";
  if (diff === 0) return "Today";
  if (diff === 1) return "Tomorrow";
  if (diff < 7) return date.toLocaleDateString("en-US", { weekday: "long" });
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

/* ─── Home Card ─── */

function HomeCard({
  data,
  basePath,
}: {
  data: MyResidenceResponse;
  basePath: string;
}) {
  const r = data.residence;
  const overdue = data.task_summary?.overdue ?? 0;
  const dueSoon = data.task_summary?.due_soon ?? 0;
  const total = data.task_summary?.total ?? 0;
  const address = [r.street_address, r.city, r.state_province]
    .filter(Boolean)
    .join(", ");
  const isGood = overdue === 0 && dueSoon === 0;

  return (
    <Link
      href={`${basePath}/residences/${r.id}`}
      className="group block"
    >
      <div className="rounded-2xl border border-border bg-card overflow-hidden transition-all duration-200 hover:shadow-[var(--shadow-warm-md)] hover:-translate-y-0.5 hover:border-border/80">
        <div className="h-1 bg-gradient-to-r from-primary/60 to-primary/20" />
        <div className="p-5 sm:p-6">
          {/* Status badge */}
          <div className="flex items-center justify-between mb-4">
            <div className="size-12 rounded-xl bg-primary/10 flex items-center justify-center">
              <Home className="size-5 text-primary" />
            </div>
            {overdue > 0 ? (
              <span className="inline-flex items-center gap-1 text-xs font-medium text-red-600 bg-red-50 dark:text-red-400 dark:bg-red-500/10 px-2.5 py-1 rounded-full">
                <CircleAlert className="size-3" />
                {overdue} overdue
              </span>
            ) : !isGood && dueSoon > 0 ? (
              <span className="inline-flex items-center gap-1 text-xs font-medium text-amber-600 bg-amber-50 dark:text-amber-400 dark:bg-amber-500/10 px-2.5 py-1 rounded-full">
                <CalendarClock className="size-3" />
                {dueSoon} coming up
              </span>
            ) : isGood && total > 0 ? (
              <span className="inline-flex items-center gap-1 text-xs font-medium text-primary bg-primary/10 px-2.5 py-1 rounded-full">
                <Sparkles className="size-3" />
                All good
              </span>
            ) : null}
          </div>

          {/* Name and address */}
          <h3 className="font-heading text-lg font-semibold leading-tight group-hover:text-primary transition-colors">
            {r.name}
          </h3>
          {address && (
            <p className="text-sm text-muted-foreground mt-1 flex items-center gap-1.5">
              <MapPin className="size-3.5 shrink-0" />
              <span className="truncate">{address}</span>
            </p>
          )}

          {/* Quick stats */}
          <div className="flex items-center gap-4 mt-4 pt-4 border-t border-border/60">
            <span className="text-xs text-muted-foreground">
              {total} {total === 1 ? "task" : "tasks"}
            </span>
            <span className="text-xs text-muted-foreground flex items-center gap-1">
              View home
              <ArrowRight className="size-3 transition-transform group-hover:translate-x-0.5" />
            </span>
          </div>
        </div>
      </div>
    </Link>
  );
}

/* ─── Needs Attention (task cards) ─── */

function NeedsAttention({
  tasks,
  basePath,
}: {
  tasks: TaskResponse[];
  basePath: string;
}) {
  if (tasks.length === 0) return null;

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="font-heading text-lg font-semibold">Needs Attention</h2>
        <Link
          href={`${basePath}/tasks`}
          className="text-sm font-medium text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1"
        >
          All tasks
          <ArrowRight className="size-3.5" />
        </Link>
      </div>

      <div className="grid sm:grid-cols-2 gap-3">
        {tasks.map((task) => {
          const dateLabel = task.next_due_date || task.due_date;
          const relative = dateLabel ? getRelativeDate(dateLabel) : null;
          const isOverdue = relative === "Overdue";
          const isToday = relative === "Today";

          return (
            <Link
              key={task.id}
              href={`${basePath}/tasks/${task.id}`}
              className="group"
            >
              <div className="flex items-center gap-3 rounded-xl border border-border bg-card p-4 transition-all duration-200 hover:shadow-[var(--shadow-warm-sm)] hover:-translate-y-0.5">
                <div
                  className={`size-2.5 rounded-full shrink-0 ${
                    isOverdue
                      ? "bg-red-500"
                      : task.in_progress
                        ? "bg-primary"
                        : "bg-border"
                  }`}
                />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold leading-snug truncate group-hover:text-primary transition-colors">
                    {task.title}
                  </p>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {task.residence_name}
                  </p>
                </div>
                {relative && (
                  <span
                    className={`text-xs font-medium shrink-0 px-2.5 py-1 rounded-full ${
                      isOverdue
                        ? "bg-red-50 text-red-600 dark:bg-red-500/10 dark:text-red-400"
                        : isToday
                          ? "bg-amber-50 text-amber-600 dark:bg-amber-500/10 dark:text-amber-400"
                          : "bg-muted text-muted-foreground"
                    }`}
                  >
                    {relative}
                  </span>
                )}
              </div>
            </Link>
          );
        })}
      </div>
    </div>
  );
}

/* ─── Loading State ─── */

function DashboardSkeleton() {
  return (
    <div className="space-y-10">
      <div className="space-y-2">
        <Skeleton className="h-8 w-64" />
        <Skeleton className="h-5 w-48" />
      </div>
      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {[1, 2, 3].map((i) => (
          <div key={i} className="rounded-2xl border bg-card p-6 space-y-4">
            <Skeleton className="size-11 rounded-xl" />
            <Skeleton className="h-5 w-3/4" />
            <Skeleton className="h-4 w-1/2" />
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─── Dashboard ─── */

export default function DashboardPage() {
  const { data: residences, isLoading: homesLoading } = useResidences();
  const { data: kanban, isLoading: tasksLoading } = useTasks();
  const user = useAuthStore((s) => s.user);
  const { basePath } = useDataProvider();

  const homes = Array.isArray(residences) ? residences : [];
  const name = user?.first_name || "";
  const greeting = `${getTimeGreeting()}${name ? `, ${name}` : ""}`;

  // Flatten all tasks from kanban columns (exclude completed/cancelled)
  const allTasks: TaskResponse[] = kanban?.columns
    ?.flatMap((col) => col.tasks)
    ?.filter((t) => !t.is_cancelled && !t.is_archived) ?? [];

  // Active tasks that need attention — overdue first, then due soonest
  const activeTasks = allTasks
    .filter((t) => {
      const col = kanban?.columns.find((c) => c.tasks.some((ct) => ct.id === t.id));
      return col?.name !== "completed_tasks";
    })
    .filter((t) => t.next_due_date || t.due_date || t.in_progress)
    .sort((a, b) => {
      const dateA = a.next_due_date || a.due_date || "";
      const dateB = b.next_due_date || b.due_date || "";
      if (!dateA) return 1;
      if (!dateB) return -1;
      return new Date(dateA).getTime() - new Date(dateB).getTime();
    })
    .slice(0, 6);

  const totalOverdue = homes.reduce(
    (sum, r) => sum + (r.task_summary?.overdue ?? 0), 0
  );

  // Status line under greeting
  const statusMsg = homes.length === 0
    ? ""
    : totalOverdue > 0
      ? totalOverdue === 1
        ? "One thing needs your attention."
        : `${totalOverdue} things need your attention.`
      : allTasks.length > 0
        ? "Everything\u2019s looking good."
        : "";

  if (homesLoading || tasksLoading) {
    return <DashboardSkeleton />;
  }

  /* ─── Empty state: no homes yet ─── */
  if (homes.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] text-center">
        <div className="size-20 rounded-3xl bg-gradient-to-br from-brand-clay-light to-brand-sage-light flex items-center justify-center mb-6">
          <Home className="size-9 text-primary" />
        </div>
        <h1 className="font-heading text-3xl font-bold tracking-tight">
          Welcome to honeyDue{name ? `, ${name}` : ""}
        </h1>
        <p className="text-muted-foreground mt-3 max-w-md text-base leading-relaxed">
          The easiest way to keep your home running smoothly.
          Add your first home to get started.
        </p>
        <Button
          asChild
          className="mt-8 rounded-full px-8 h-12 text-base"
        >
          <Link href={`${basePath}/residences/new`}>
            <Plus className="size-5 mr-2" />
            Add Your Home
          </Link>
        </Button>

        <div className="grid sm:grid-cols-3 gap-5 mt-16 max-w-xl w-full">
          {[
            {
              icon: CheckSquare,
              title: "Track tasks",
              body: "Repairs, maintenance, projects — all in one place.",
            },
            {
              icon: HardHat,
              title: "Save your pros",
              body: "Never lose a good contractor\u2019s number again.",
            },
            {
              icon: FileText,
              title: "Store documents",
              body: "Warranties, manuals, receipts — easy to find.",
            },
          ].map((tip) => (
            <div key={tip.title} className="text-center">
              <tip.icon className="size-5 text-muted-foreground mx-auto mb-2" />
              <p className="text-sm font-medium">{tip.title}</p>
              <p className="text-xs text-muted-foreground mt-1 leading-relaxed">
                {tip.body}
              </p>
            </div>
          ))}
        </div>
      </div>
    );
  }

  /* ─── Quick action pill data ─── */
  const quickActions = [
    { label: "Add task", href: `${basePath}/tasks/new`, icon: CheckSquare },
    { label: "Add pro", href: `${basePath}/contractors/new`, icon: HardHat },
    { label: "Save doc", href: `${basePath}/documents/new`, icon: FileText },
    { label: "Add home", href: `${basePath}/residences/new`, icon: Home },
  ];

  /* ─── Main dashboard ─── */
  return (
    <div className="space-y-10">
      {/* Hero — Greeting + inline quick actions */}
      <div>
        <h1 className="font-heading text-2xl sm:text-3xl font-bold tracking-tight">
          {greeting}
        </h1>
        {statusMsg && (
          <p className="text-muted-foreground mt-1.5 text-[15px]">{statusMsg}</p>
        )}
        <div className="flex flex-wrap gap-2 mt-4">
          {quickActions.map((a) => (
            <Link
              key={a.href}
              href={a.href}
              className="inline-flex items-center gap-1.5 rounded-full border border-border bg-card px-4 py-2.5 text-xs font-medium text-muted-foreground hover:text-foreground hover:border-primary/30 hover:shadow-[var(--shadow-warm-sm)] transition-all"
            >
              <a.icon className="size-3.5" />
              {a.label}
            </Link>
          ))}
        </div>
      </div>

      {/* Needs Attention — overdue and upcoming tasks */}
      <NeedsAttention tasks={activeTasks} basePath={basePath} />

      {/* Your Homes — dropped to #3 */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-heading text-lg font-semibold">Your Homes</h2>
          <Link
            href={`${basePath}/residences/new`}
            className="inline-flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
          >
            <Plus className="size-3.5" />
            Add
          </Link>
        </div>

        <div className={`grid gap-5 ${
          homes.length === 1
            ? "grid-cols-1 max-w-lg"
            : "sm:grid-cols-2 lg:grid-cols-3"
        }`}>
          {homes.map((home) => (
            <HomeCard key={home.residence.id} data={home} basePath={basePath} />
          ))}
        </div>
      </div>

      {/* Template suggestions — at the bottom */}
      <TemplateSuggestions hasResidences={homes.length > 0} activeTaskCount={allTasks.length} />
    </div>
  );
}
