"use client";

import { useEffect, useState } from "react";
import { useAuth } from "@/lib/auth-context";
import { usePermissions } from "@/hooks/use-permissions";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Building2,
  BookOpen,
  Home,
  Newspaper,
  TrendingUp,
  Users,
  DollarSign,
} from "lucide-react";
import api from "@/lib/api";

interface RecentActivityDay {
  date: string;
  properties: number;
  companies: number;
  posts: number;
}

interface DashboardStats {
  total_properties: number;
  total_companies: number;
  total_posts: number;
  total_magazine_issues: number;
  total_users?: number;
  active_subscriptions?: number;
  recent_activity?: RecentActivityDay[];
}

export default function DashboardPage() {
  const { user } = useAuth();
  const { isAdmin, isContentManager } = usePermissions();
  const [stats, setStats] = useState<DashboardStats | null>(null);

  useEffect(() => {
    api.get("/api/dashboard/stats").then(({ data }) => setStats(data.data)).catch(() => {});
  }, []);

  if (!user) return null;

  const initials = user.name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);

  return (
    <div className="space-y-4 sm:space-y-6">
      {/* Page header */}
      <div>
        <h1 className="font-display text-xl font-semibold text-foreground sm:text-2xl">
          Dashboard
        </h1>
        <p className="text-xs text-muted-foreground sm:text-sm">
          Welcome back, {user.name.split(" ")[0]}. Here&apos;s what&apos;s happening today.
        </p>
      </div>

      {/* Stats grid - content stats visible to admin/content managers */}
      {(isAdmin || isContentManager) && (
        <div className="grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4">
          <StatsCard
            title="Total Properties"
            value={String(stats?.total_properties ?? "—")}
            description="Active listings"
            icon={Home}
          />
          <StatsCard
            title="Companies"
            value={String(stats?.total_companies ?? "—")}
            description="In directory"
            icon={Building2}
          />
          <StatsCard
            title="Blog Posts"
            value={String(stats?.total_posts ?? "—")}
            description="Published"
            icon={BookOpen}
          />
          <StatsCard
            title="Magazine Issues"
            value={String(stats?.total_magazine_issues ?? "—")}
            description="Total issues"
            icon={Newspaper}
          />
        </div>
      )}

      {/* Admin-only stats */}
      {isAdmin && (
        <div className="grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-2">
          <StatsCard
            title="Total Users"
            value={String(stats?.total_users ?? "—")}
            description="Registered users"
            icon={Users}
          />
          <StatsCard
            title="Subscriptions"
            value={String(stats?.active_subscriptions ?? "—")}
            description="Magazine subscribers"
            icon={DollarSign}
          />
        </div>
      )}

      {/* Content area */}
      <div className="grid gap-4 sm:gap-6 lg:grid-cols-3">
        {/* Profile card */}
        <Card className="lg:col-span-1">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Your Profile
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-3">
              <Avatar className="h-12 w-12">
                <AvatarImage src={user.avatar || undefined} />
                <AvatarFallback className="bg-primary/10 text-sm font-medium text-primary">
                  {initials}
                </AvatarFallback>
              </Avatar>
              <div>
                <p className="font-medium text-foreground">{user.name}</p>
                <p className="text-sm text-muted-foreground">{user.email}</p>
              </div>
            </div>
            <Separator />
            <dl className="space-y-3 text-sm">
              <div className="flex justify-between">
                <dt className="text-muted-foreground">Roles</dt>
                <dd className="flex gap-1">
                  {user.roles.map((role, index) => {
                    const roleName = typeof role === 'string' ? role : role.name;
                    return (
                      <Badge
                        key={roleName ?? index}
                        variant="secondary"
                        className="capitalize text-xs"
                      >
                        {roleName}
                      </Badge>
                    );
                  })}
                </dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-muted-foreground">Phone</dt>
                <dd className="font-medium text-foreground">
                  {user.phone || "Not set"}
                </dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-muted-foreground">Location</dt>
                <dd className="font-medium text-foreground">
                  {user.city && user.country_of_residence
                    ? `${user.city}, ${user.country_of_residence}`
                    : user.country_of_residence || "Not set"}
                </dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-muted-foreground">Member since</dt>
                <dd className="font-medium text-foreground">
                  {new Date(user.created_at).toLocaleDateString("en-GB", {
                    month: "short",
                    year: "numeric",
                  })}
                </dd>
              </div>
            </dl>
          </CardContent>
        </Card>

        {/* Recent Activity */}
        <Card className="lg:col-span-2">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Recent Activity (Last 7 days)
            </CardTitle>
          </CardHeader>
          <CardContent>
            {stats?.recent_activity && stats.recent_activity.some(d => d.properties + d.companies + d.posts > 0) ? (
              <div className="space-y-3">
                {stats.recent_activity.map((day) => {
                  const total = day.properties + day.companies + day.posts;
                  if (total === 0) return null;
                  return (
                    <div key={day.date} className="flex items-center justify-between rounded-md border px-3 py-2">
                      <span className="text-sm font-medium text-foreground">{day.date}</span>
                      <div className="flex gap-3 text-xs text-muted-foreground">
                        {day.properties > 0 && (
                          <span className="flex items-center gap-1">
                            <Home className="h-3 w-3" /> {day.properties} property{day.properties > 1 ? "ies" : "y"}
                          </span>
                        )}
                        {day.companies > 0 && (
                          <span className="flex items-center gap-1">
                            <Building2 className="h-3 w-3" /> {day.companies} company{day.companies > 1 ? "ies" : "y"}
                          </span>
                        )}
                        {day.posts > 0 && (
                          <span className="flex items-center gap-1">
                            <BookOpen className="h-3 w-3" /> {day.posts} post{day.posts > 1 ? "s" : ""}
                          </span>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center py-8 text-center sm:py-12">
                <div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted sm:h-12 sm:w-12">
                  <TrendingUp className="h-4 w-4 text-muted-foreground sm:h-5 sm:w-5" />
                </div>
                <p className="mt-4 text-sm font-medium text-foreground">
                  No recent activity
                </p>
                <p className="mt-1 text-sm text-muted-foreground">
                  Your recent actions will appear here once you start managing content.
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function StatsCard({
  title,
  value,
  description,
  icon: Icon,
  trend,
}: {
  title: string;
  value: string;
  description: string;
  icon: React.ComponentType<{ className?: string }>;
  trend?: string;
}) {
  return (
    <Card>
      <CardContent className="p-4 sm:p-6">
        <div className="flex items-center justify-between gap-2">
          <div className="min-w-0 space-y-0.5 sm:space-y-1">
            <p className="truncate text-xs font-medium text-muted-foreground sm:text-sm">{title}</p>
            <p className="text-lg font-semibold tracking-tight text-foreground sm:text-2xl">
              {value}
            </p>
            <p className="hidden text-xs text-muted-foreground sm:block">{description}</p>
          </div>
          <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/10 sm:h-10 sm:w-10">
            <Icon className="h-4 w-4 text-primary sm:h-5 sm:w-5" />
          </div>
        </div>
        {trend && (
          <p className="mt-2 hidden items-center gap-1 text-xs text-muted-foreground sm:mt-3 sm:flex">
            <TrendingUp className="h-3 w-3" />
            {trend}
          </p>
        )}
      </CardContent>
    </Card>
  );
}
