import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  UserOutlined,
  UserSwitchOutlined,
  DollarOutlined,
  ReloadOutlined,
  ShopOutlined,
} from "@ant-design/icons";

import StatCard from "../../components/Dashboard/StatCard";
import SalesProfitChart from "../../components/Dashboard/SalesProfitChart";
import { ExpenseChart } from "../../components/Dashboard/ExpenseChart";
import OutstandingAccounts from "../../components/Dashboard/OutstandingAccounts";
import AttendanceCard from "../../components/Dashboard/AttendanceCard";
import VegetableStockList from "../../components/Dashboard/VegetableStockList";
import TopDemandedVegetables from "../../components/Dashboard/TopDemandedVegetables";
import RecentSales from "../../components/Dashboard/RecentSales";
import { Col, Row, Button, Tooltip } from "antd";
import jwtAxios from "../../api/axiosInstance";
import { ENDPOINTS } from "../../api/endpoints";
import { useEffect, useState } from "react";
import type { DashboardData } from "../../types/dashboard";
import { useAppSelector } from "../../redux/hooks";

const DashboardPage = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [dashboardData, setDashboardData] = useState<DashboardData | null>(null);
  const [lastRefreshed, setLastRefreshed] = useState<Date>(new Date());
  const [now, setNow] = useState<Date>(new Date());

  // Live clock — tick every minute
  useEffect(() => {
    const timer = setInterval(() => setNow(new Date()), 60000);
    return () => clearInterval(timer);
  }, []);

  const user = useAppSelector((state) => state.auth.user);
  const userName = user?.name ?? "User";
  const firstName = userName;

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      const response = await jwtAxios.get(ENDPOINTS.DASHBOARD);
      setDashboardData(response.data.data);
      setLastRefreshed(new Date());
    } catch (error) {
      console.error("Error fetching dashboard data:", error);
    } finally {
      setLoading(false);
    }
  };

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

  // ── Derived values with safe fallbacks ──────────────────────────────────────
  const statCards = dashboardData?.statCards;
  const chartData = dashboardData?.salesProfitChart ?? [];
  const outstanding = dashboardData?.outstandingAccounts;
  const vegetableStock = dashboardData?.vegetableStock ?? [];
  const topDemand = dashboardData?.topDemandedVegetables ?? [];
  const recentSales = dashboardData?.recentSales ?? [];

  // ── Greeting based on hour ───────────────────────────────────────────────────
  const hour = now.getHours();
  const greeting =
    hour < 12 ? "Good Morning" : hour < 17 ? "Good Afternoon" : "Good Evening";
  const greetingEmoji = hour < 12 ? "🌤️" : hour < 17 ? "☀️" : "🌙";

  const dateLabel = now.toLocaleDateString("en-IN", {
    weekday: "long",
    day: "numeric",
    month: "long",
    year: "numeric",
  });
  const timeLabel = now.toLocaleTimeString("en-IN", {
    hour: "2-digit",
    minute: "2-digit",
    hour12: true,
  });
  const refreshLabel = lastRefreshed.toLocaleTimeString("en-IN", {
    hour: "2-digit",
    minute: "2-digit",
  });


  const statCardConfig = [
    {
      title: "Today's Purchases",
      value: `₹${Number(statCards?.todaysPurchaseAmount ?? 0).toLocaleString()}`,
      subtitle: "Total purchase spend today",
      icon: <ArrowDownOutlined />,
      gradient: "linear-gradient(135deg, #f97316 0%, #ea580c 100%)",
      iconBg: "rgba(255,255,255,0.25)",
    },
    {
      title: "Today's Sales",
      value: `₹${Number(statCards?.todaysSalesAmount ?? 0).toLocaleString()}`,
      subtitle: "Revenue collected today",
      icon: <ArrowUpOutlined />,
      gradient: "linear-gradient(135deg, #10b981 0%, #059669 100%)",
      iconBg: "rgba(255,255,255,0.25)",
    },
    {
      title: "Today's Expenses",
      value: `₹${Number(statCards?.todaysExpensesAmount ?? 0).toLocaleString()}`,
      subtitle: "Operating costs today",
      icon: <DollarOutlined />,
      gradient: "linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)",
      iconBg: "rgba(255,255,255,0.25)",
    },
    {
      title: "Today's Retail Sales",
      value: `₹${Number(statCards?.todaysRetailSalesAmount ?? 0).toLocaleString()}`,
      subtitle: "Retail revenue collected today",
      icon: <ShopOutlined />,
      gradient: "linear-gradient(135deg, #06b6d4 0%, #0891b2 100%)",
      iconBg: "rgba(255,255,255,0.25)",
    },
    {
      title: "Active Customers",
      value: Number(statCards?.totalCustomers ?? 0).toLocaleString(),
      subtitle: "Registered & active",
      icon: <UserSwitchOutlined />,
      gradient: "linear-gradient(135deg, #ec4899 0%, #db2777 100%)",
      iconBg: "rgba(255,255,255,0.25)",
    },
    {
      title: "Active Suppliers",
      value: Number(statCards?.totalSellers ?? 0).toLocaleString(),
      subtitle: "Registered vendors",
      icon: <UserOutlined />,
      gradient: "linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)",
      iconBg: "rgba(255,255,255,0.25)",
    },
  ];

  // Last refreshed label — now computed above

  return (
    <div style={{ minHeight: "100vh" }}>

      {/* ── Welcome Banner ─────────────────────────────────────────────────── */}
      <div style={{
        position: "relative",
        borderRadius: 24,
        overflow: "hidden",
        marginBottom: 28,
        background: "linear-gradient(135deg, #0f172a 0%, #1e3a5f 40%, #0f4c81 70%, #1d6fa4 100%)",
        boxShadow: "0 12px 48px rgba(15,23,42,0.35)",
        minHeight: 140,
      }}>
        {/* Animated shimmer overlay */}
        <div style={{
          position: "absolute", inset: 0, pointerEvents: "none",
          background: "linear-gradient(105deg, transparent 30%, rgba(255,255,255,0.07) 50%, transparent 70%)",
          backgroundSize: "200% 100%",
          animation: "shimmer 3.5s ease-in-out infinite",
        }} />

        {/* Decorative circles */}
        <div style={{ position: "absolute", top: -50, right: -50, width: 200, height: 200, borderRadius: "50%", background: "rgba(255,255,255,0.04)", pointerEvents: "none" }} />
        <div style={{ position: "absolute", bottom: -60, right: 120, width: 160, height: 160, borderRadius: "50%", background: "rgba(255,255,255,0.04)", pointerEvents: "none" }} />
        <div style={{ position: "absolute", top: 20, right: 200, width: 80, height: 80, borderRadius: "50%", background: "rgba(255,255,255,0.06)", pointerEvents: "none" }} />

        {/* Content */}
        <div style={{
          position: "relative",
          zIndex: 1,
          padding: "28px 32px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          flexWrap: "wrap",
          gap: 16,
        }}>
          {/* Left — Greeting */}
          <div>
            {/* Shop badge */}
            <div style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
              background: "rgba(255,255,255,0.12)",
              border: "1px solid rgba(255,255,255,0.18)",
              borderRadius: 20,
              padding: "4px 14px",
              marginBottom: 14,
              backdropFilter: "blur(8px)",
            }}>
              <ShopOutlined style={{ color: "#93c5fd", fontSize: 13 }} />
              <span style={{ color: "#bfdbfe", fontSize: 12, fontWeight: 600, letterSpacing: "0.05em" }}>
                AVS Vegetable Management
              </span>
            </div>

            {/* Greeting line */}
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <h1 style={{
                fontSize: 28,
                fontWeight: 800,
                color: "#fff",
                margin: 0,
                letterSpacing: "-0.5px",
                lineHeight: 1.2,
                textShadow: "0 2px 8px rgba(0,0,0,0.3)",
              }}>
                {greeting}, {firstName}!
              </h1>
              <span style={{ fontSize: 26 }}>{greetingEmoji}</span>
            </div>

            {/* Sub-message */}
            <p style={{
              color: "rgba(186,230,253,0.85)",
              fontSize: 14,
              marginTop: 8,
              marginBottom: 0,
              fontWeight: 500,
            }}>
              Here's what's happening at your store today.
            </p>

            {/* Date & time row */}
            <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 16, flexWrap: "wrap" }}>
              {/* Date pill */}
              <div style={{
                display: "flex",
                alignItems: "center",
                gap: 7,
                background: "rgba(255,255,255,0.10)",
                border: "1px solid rgba(255,255,255,0.15)",
                borderRadius: 10,
                padding: "5px 14px",
              }}>
                <span style={{ fontSize: 14 }}>📅</span>
                <span style={{ color: "#e0f2fe", fontSize: 13, fontWeight: 600 }}>{dateLabel}</span>
              </div>

              {/* Time pill */}
              <div style={{
                display: "flex",
                alignItems: "center",
                gap: 7,
                background: "rgba(255,255,255,0.10)",
                border: "1px solid rgba(255,255,255,0.15)",
                borderRadius: 10,
                padding: "5px 14px",
              }}>
                <span style={{ fontSize: 14 }}>🕐</span>
                <span style={{ color: "#e0f2fe", fontSize: 13, fontWeight: 600 }}>{timeLabel}</span>
              </div>

            </div>
          </div>

          {/* Right — Refresh button */}
          <Tooltip title={`Data refreshed at ${refreshLabel}`}>
            <Button
              icon={<ReloadOutlined spin={loading} />}
              onClick={fetchDashboardData}
              loading={loading}
              size="large"
              style={{
                borderRadius: 14,
                fontWeight: 700,
                background: "rgba(255,255,255,0.12)",
                border: "1px solid rgba(255,255,255,0.25)",
                color: "#fff",
                boxShadow: "0 4px 16px rgba(0,0,0,0.2)",
                backdropFilter: "blur(8px)",
                height: 44,
                paddingInline: 20,
                transition: "all 0.2s ease",
              }}
            >
              Refresh
            </Button>
          </Tooltip>
        </div>

        {/* Keyframe for shimmer */}
        <style>{`
          @keyframes shimmer {
            0%   { background-position: 200% 0; }
            100% { background-position: -200% 0; }
          }
        `}</style>
      </div>

      {/* ── 6 Stat Cards ─────────────────────────────────────────────────── */}
      <Row gutter={[20, 20]}>
        {statCardConfig.map((card) => (
          <Col xs={24} sm={12} xl={8} key={card.title}>
            <StatCard {...card} loading={loading} />
          </Col>
        ))}
      </Row>

      {/* ── Attendance + Outstanding ───────────────────────────────────────────── */}
      <Row gutter={[20, 20]} style={{ marginTop: 20 }}>
        <Col xs={24} lg={12} xl={12}>
          <AttendanceCard data={(dashboardData as any)?.todaysAttendance} loading={loading} />
        </Col>
        <Col xs={24} lg={12} xl={12}>
          <OutstandingAccounts
            pendingVendorPayments={outstanding?.pendingVendorPayments ?? 0}
            pendingCustomerReceipts={outstanding?.pendingCustomerReceipts ?? 0}
            vendorPayments={outstanding?.vendorPayments}
            customerReceipts={outstanding?.customerReceipts}
            loading={loading}
          />
        </Col>
      </Row>

      {/* ── Chart ───────────────────────────────────────────────────────────── */}
      <Row gutter={[20, 20]} style={{ marginTop: 20 }}>
        <Col span={24}>
          <SalesProfitChart data={chartData} loading={loading} />
        </Col>
      </Row>

      {/* ── Expense Chart ────────────────────────────────────────────────── */}
      <Row gutter={[20, 20]} style={{ marginTop: 20 }}>
        <Col span={24}>
          <ExpenseChart />
        </Col>
      </Row>

      {/* ── Recent Sales + Low Stock + Top Demand ────────────────────────── */}
      <Row gutter={[20, 20]} style={{ marginTop: 20 }}>
        <Col xs={24} lg={12} xl={8}>
          <RecentSales data={recentSales} loading={loading} />
        </Col>
        <Col xs={24} lg={12} xl={8}>
          <VegetableStockList data={vegetableStock} loading={loading} />
        </Col>
        <Col xs={24} xl={8}>
          <TopDemandedVegetables data={topDemand} loading={loading} />
        </Col>
      </Row>

    </div>
  );
};

export default DashboardPage;