"use client";

import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Building2, FileText, Home, TrendingUp, Users } from "lucide-react";
import api from "@/lib/api";
import { toast } from "sonner";

const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });

interface DashboardStats {
  total_properties: number;
  total_companies: number;
  total_posts: number;
  total_users: number;
  monthly_listings: { month: string; count: number }[];
  property_by_type: { type: string; count: number }[];
  property_status: { status: string; count: number }[];
  recent_activity: { date: string; properties: number; companies: number; posts: number }[];
}

function StatCard({ title, value, icon: Icon, trend }: { title: string; value: string | number; icon: any; trend?: string }) {
  return (
    <Card>
      <CardContent className="flex items-center gap-4 p-4">
        <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-primary/10">
          <Icon className="h-6 w-6 text-primary" />
        </div>
        <div>
          <p className="text-sm text-muted-foreground">{title}</p>
          <p className="text-2xl font-semibold">{typeof value === "number" ? value.toLocaleString() : value}</p>
          {trend && <p className="text-xs text-green-600">{trend}</p>}
        </div>
      </CardContent>
    </Card>
  );
}

export default function AnalyticsPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const { data } = await api.get("/api/dashboard/stats");
        setStats(data.data);
      } catch {
        // Use mock data if endpoint doesn't exist yet
        setStats({
          total_properties: 124,
          total_companies: 89,
          total_posts: 56,
          total_users: 342,
          monthly_listings: [
            { month: "Jan", count: 12 },
            { month: "Feb", count: 18 },
            { month: "Mar", count: 15 },
            { month: "Apr", count: 22 },
            { month: "May", count: 28 },
            { month: "Jun", count: 35 },
          ],
          property_by_type: [
            { type: "Sale", count: 68 },
            { type: "Rent", count: 42 },
            { type: "Lease", count: 14 },
          ],
          property_status: [
            { status: "Published", count: 85 },
            { status: "Draft", count: 24 },
            { status: "Pending", count: 15 },
          ],
          recent_activity: [
            { date: "Mon", properties: 4, companies: 2, posts: 3 },
            { date: "Tue", properties: 6, companies: 1, posts: 5 },
            { date: "Wed", properties: 3, companies: 4, posts: 2 },
            { date: "Thu", properties: 8, companies: 3, posts: 4 },
            { date: "Fri", properties: 5, companies: 2, posts: 6 },
            { date: "Sat", properties: 2, companies: 1, posts: 1 },
            { date: "Sun", properties: 1, companies: 0, posts: 2 },
          ],
        });
      } finally {
        setLoading(false);
      }
    };
    fetchStats();
  }, []);

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <Card key={i}><CardContent className="p-4"><Skeleton className="h-16 w-full" /></CardContent></Card>
          ))}
        </div>
        <div className="grid gap-6 lg:grid-cols-2">
          <Card><CardContent className="p-4"><Skeleton className="h-64 w-full" /></CardContent></Card>
          <Card><CardContent className="p-4"><Skeleton className="h-64 w-full" /></CardContent></Card>
        </div>
      </div>
    );
  }

  if (!stats) return null;

  const areaChartOptions: ApexCharts.ApexOptions = {
    chart: { type: "area", toolbar: { show: false }, fontFamily: "inherit" },
    colors: ["#1a2b4a", "#c8a94e", "#2d8a4e"],
    dataLabels: { enabled: false },
    stroke: { curve: "smooth", width: 2 },
    xaxis: { categories: stats.recent_activity.map((d) => d.date) },
    yaxis: { labels: { formatter: (val) => Math.round(val).toString() } },
    legend: { position: "top" },
    fill: { type: "gradient", gradient: { opacityFrom: 0.4, opacityTo: 0.1 } },
    tooltip: { theme: "dark" },
  };

  const areaChartSeries = [
    { name: "Properties", data: stats.recent_activity.map((d) => d.properties) },
    { name: "Companies", data: stats.recent_activity.map((d) => d.companies) },
    { name: "Posts", data: stats.recent_activity.map((d) => d.posts) },
  ];

  const barChartOptions: ApexCharts.ApexOptions = {
    chart: { type: "bar", toolbar: { show: false }, fontFamily: "inherit" },
    colors: ["#1a2b4a"],
    dataLabels: { enabled: false },
    xaxis: { categories: stats.monthly_listings.map((d) => d.month) },
    yaxis: { labels: { formatter: (val) => Math.round(val).toString() } },
    plotOptions: { bar: { borderRadius: 4, columnWidth: "60%" } },
    tooltip: { theme: "dark" },
  };

  const barChartSeries = [
    { name: "Listings", data: stats.monthly_listings.map((d) => d.count) },
  ];

  const donutChartOptions: ApexCharts.ApexOptions = {
    chart: { type: "donut", fontFamily: "inherit" },
    labels: stats.property_by_type.map((d) => d.type),
    colors: ["#1a2b4a", "#c8a94e", "#2d8a4e"],
    legend: { position: "bottom" },
    dataLabels: { enabled: true },
  };

  const donutChartSeries = stats.property_by_type.map((d) => d.count);

  const statusChartOptions: ApexCharts.ApexOptions = {
    chart: { type: "bar", toolbar: { show: false }, fontFamily: "inherit" },
    colors: ["#2d8a4e", "#c8a94e", "#1a2b4a", "#e74c3c"],
    plotOptions: { bar: { horizontal: true, borderRadius: 4, barHeight: "60%" } },
    dataLabels: { enabled: true },
    xaxis: { categories: (stats.property_status ?? []).map((d) => d.status) },
    yaxis: { labels: { style: { fontSize: "13px" } } },
    tooltip: { theme: "dark" },
  };

  const statusChartSeries = [
    { name: "Properties", data: (stats.property_status ?? []).map((d) => d.count) },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="font-display text-2xl font-semibold">Analytics</h1>
        <p className="text-sm text-muted-foreground">Overview of platform performance</p>
      </div>

      {/* Stats Grid */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard title="Properties" value={stats.total_properties} icon={Home} />
        <StatCard title="Companies" value={stats.total_companies} icon={Building2} />
        <StatCard title="Blog Posts" value={stats.total_posts} icon={FileText} />
        <StatCard title="Users" value={stats.total_users} icon={Users} />
      </div>

      {/* Charts Row 1 */}
      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Weekly Activity</CardTitle>
          </CardHeader>
          <CardContent>
            <Chart options={areaChartOptions} series={areaChartSeries} type="area" height={280} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">Monthly Listings</CardTitle>
          </CardHeader>
          <CardContent>
            <Chart options={barChartOptions} series={barChartSeries} type="bar" height={280} />
          </CardContent>
        </Card>
      </div>

      {/* Charts Row 2 */}
      <div className="grid gap-6 lg:grid-cols-3">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Properties by Type</CardTitle>
          </CardHeader>
          <CardContent className="flex items-center justify-center">
            <Chart options={donutChartOptions} series={donutChartSeries} type="donut" height={250} width={280} />
          </CardContent>
        </Card>

        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="text-base">Properties by Status</CardTitle>
          </CardHeader>
          <CardContent>
            {(stats.property_status ?? []).length > 0 ? (
              <Chart options={statusChartOptions} series={statusChartSeries} type="bar" height={250} />
            ) : (
              <p className="text-sm text-muted-foreground py-4">No status data yet</p>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
