import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Buildings,
  Users,
  Briefcase,
  TrendUp,
  UserPlus,
  CalendarBlank,
  CurrencyDollar,
  ChartLineUp,
  ArrowRight,
  Wallet,
  Clock,
  CheckCircle,
  Warning,
  Lightning,
  ChartPieSlice,
  Receipt,
  ShieldCheck,
  ArrowUp,
  ArrowDown,
} from "@phosphor-icons/react";
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import axios from "axios";
import useAuthStore from "../store/authStore";
import toast from "react-hot-toast";

export default function Dashboard() {
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const { user, isSuperAdmin } = useAuthStore();
  const [showAssetModal, setShowAssetModal] = useState(false);
  const [assetForm, setAssetForm] = useState({
    name: "",
    category: "other",
    purchase_value: "",
    current_value: "",
    purchase_date: "",
    vendor_name: "",
    location: "",
    notes: "",
  });
  const [assetReceipt, setAssetReceipt] = useState(null);

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

  const fetchDashboardData = async () => {
    try {
      const response = await axios.get("/api/dashboard");
      console.log("Dashboard API response:", response.data);
      setStats(response.data);
    } catch (error) {
      console.error("Failed to fetch dashboard data:", error);
      const msg =
        error.response?.data?.message ||
        error.message ||
        "Failed to load dashboard data";
      toast.error(`Dashboard Error: ${msg}`);
      setStats({});
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div
        className="flex items-center justify-center h-screen"
        style={{ background: "linear-gradient(135deg,#EFEBE9,#EFEBE9)" }}
      >
        <div className="flex flex-col items-center gap-4">
          <div
            className="animate-spin rounded-full h-16 w-16 border-4 border-t-transparent"
            style={{ borderColor: "#5D403733", borderTopColor: "#5D4037" }}
          ></div>
          <p className="text-gray-500 font-medium animate-pulse">
            Loading dashboard...
          </p>
        </div>
      </div>
    );
  }

  const hireData = (
    stats?.monthly_hire_trend ||
    stats?.monthly_employee_growth ||
    []
  ).map((item) => ({
    month: item.month,
    hires: item.count,
  }));

  const quickActions = isSuperAdmin()
    ? [
        {
          label: "Group Dashboard",
          href: "/group-dashboard",
          icon: ChartPieSlice,
          color: "from-indigo-700 to-primary-700",
          style: { background: "linear-gradient(135deg,#5D4037,#6D4C41)" },
        },
        {
          label: "Manage Roles",
          href: "/roles",
          icon: ShieldCheck,
          color: "from-purple-500 to-purple-600",
        },
        {
          label: "Loan Requests",
          href: "/loans",
          icon: CurrencyDollar,
          color: "from-green-500 to-green-600",
        },
        {
          label: "Profit Allocation",
          href: "/profit-sweeps",
          icon: TrendUp,
          color: "from-orange-500 to-orange-600",
        },
      ]
    : [
        {
          label: "Company Analytics",
          href: "/company-dashboard",
          icon: ChartLineUp,
          color: "from-indigo-700 to-primary-700",
          style: { background: "linear-gradient(135deg,#5D4037,#6D4C41)" },
        },
        {
          label: "Request Loan",
          href: "/loans",
          icon: CurrencyDollar,
          color: "from-green-500 to-green-600",
        },
        {
          label: "Profit Allocation",
          href: "/profit-sweeps",
          icon: TrendUp,
          color: "from-purple-500 to-purple-600",
        },
        {
          label: "Monthly Financials",
          href: "/monthly-financials",
          icon: CalendarBlank,
          color: "from-cyan-500 to-cyan-600",
        },
        {
          label: "Expenses",
          href: "/expenses",
          icon: Receipt,
          color: "from-orange-500 to-orange-600",
        },
      ];

  return (
    <div className="space-y-8">
      {/* Welcome Header */}
      <div
        className="rounded-2xl p-8 text-white shadow-xl"
        style={{
          background:
            "linear-gradient(135deg,#3E2723 0%,#5D4037 60%,#6D4C41 100%)",
        }}
      >
        <div className="flex items-center justify-between">
          <div>
            <p className="text-primary-200 text-sm font-medium mb-1">
              {new Date().toLocaleDateString("en-US", {
                weekday: "long",
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </p>
            <h1 className="text-3xl font-bold mb-2">
              Welcome back, {user?.name?.split(" ")[0]}
            </h1>
            <p className="text-primary-100">
              {isSuperAdmin()
                ? "Sarkin Mota Group — Super Admin Overview"
                : `${user?.company?.name || "Company"} — Dashboard`}
            </p>
          </div>
          <div className="hidden md:block">
            <Lightning size={80} weight="duotone" className="text-white/20" />
          </div>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        {isSuperAdmin() ? (
          <>
            <KpiCard
              icon={CurrencyDollar}
              iconColor="brown"
              title="Total Revenue"
              value={stats?.financials?.total_revenue || 0}
              subtitle="All companies"
            />
            <KpiCard
              icon={Receipt}
              iconColor="purple"
              title="Total Expenses"
              value={stats?.financials?.total_expenses || 0}
              subtitle="Expenses + payable invoices"
            />
            <KpiCard
              icon={Wallet}
              iconColor="green"
              title="Net Profit"
              value={stats?.financials?.net_profit || 0}
              subtitle="Aggregated net profit"
            />
            <KpiCard
              icon={Buildings}
              iconColor="orange"
              title="Cash & Banks"
              value={stats?.financials?.total_cash_and_banks || 0}
              subtitle="Cash + bank balances"
            />
          </>
        ) : (
          <>
            <KpiCard
              icon={Users}
              iconColor="brown"
              title="Total Employees"
              value={stats?.total_employees || 0}
              subtitle={`${stats?.active_employees || 0} active`}
              trend="up"
              trendValue="5%"
            />
            <KpiCard
              icon={Briefcase}
              iconColor="purple"
              title="Departments"
              value={stats?.total_departments || 0}
              subtitle="Company departments"
            />
            <KpiCard
              icon={UserPlus}
              iconColor="green"
              title="System Users"
              value={stats?.total_users || 0}
              subtitle="Active users"
            />
            <KpiCard
              icon={TrendUp}
              iconColor="orange"
              title="New This Month"
              value={
                stats?.monthly_hire_trend?.[stats.monthly_hire_trend.length - 1]
                  ?.count || 0
              }
              subtitle="Recent hires"
              trend="up"
              trendValue="15%"
            />
          </>
        )}
      </div>

      {/* Quick Actions */}
      <div>
        <h2 className="text-lg font-bold text-gray-900 mb-4">Quick Actions</h2>
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {quickActions.map((action, idx) => (
            <Link
              key={idx}
              to={action.href}
              className={`bg-gradient-to-br ${action.color} rounded-2xl p-5 text-white hover:shadow-xl transition-all duration-200 hover:-translate-y-1 group`}
              style={action.style || {}}
            >
              <action.icon
                size={32}
                weight="duotone"
                className="mb-3 opacity-90"
              />
              <p className="font-semibold text-sm">{action.label}</p>
              <ArrowRight
                size={16}
                weight="bold"
                className="mt-2 opacity-0 group-hover:opacity-100 transition-opacity"
              />
            </Link>
          ))}
        </div>
      </div>

      {isSuperAdmin() && (
        <div className="flex items-center gap-3">
          <button
            onClick={() => setShowAssetModal(true)}
            className="px-4 py-2 rounded-xl bg-green-600 text-white text-sm font-semibold hover:bg-green-700"
          >
            Add Holding Asset
          </button>
          <span className="text-sm text-gray-500">
            Create an asset under the Holding company
          </span>
        </div>
      )}

      {/* Charts Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Hiring Trend */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
              <ChartLineUp
                size={24}
                className="text-primary-600"
                weight="duotone"
              />
              Hiring Trend
            </h3>
            <span className="text-xs bg-primary-50 text-primary-600 px-3 py-1 rounded-full font-semibold">
              Last 6 months
            </span>
          </div>
          <ResponsiveContainer width="100%" height={280}>
            <AreaChart data={hireData}>
              <defs>
                <linearGradient id="hireGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#5D4037" stopOpacity={0.25} />
                  <stop offset="95%" stopColor="#5D4037" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis
                dataKey="month"
                stroke="#9ca3af"
                style={{ fontSize: 12 }}
              />
              <YAxis
                stroke="#9ca3af"
                style={{ fontSize: 12 }}
                allowDecimals={false}
              />
              <Tooltip
                contentStyle={{
                  borderRadius: "12px",
                  border: "1px solid #e5e7eb",
                }}
              />
              <Area
                type="monotone"
                dataKey="hires"
                stroke="#5D4037"
                strokeWidth={3}
                fill="url(#hireGradient)"
              />
            </AreaChart>
          </ResponsiveContainer>
        </div>

        {/* Recent Hires */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
              <Users size={24} className="text-purple-600" weight="duotone" />
              Recent Hires
            </h3>
            <Link
              to="/employees"
              className="text-xs bg-purple-50 text-purple-600 px-3 py-1 rounded-full font-semibold hover:bg-purple-100"
            >
              View All
            </Link>
          </div>
          <div className="space-y-3">
            {(stats?.recent_hires || []).slice(0, 5).map((employee) => (
              <div
                key={employee.id}
                className="flex items-center justify-between p-3 bg-gradient-to-r from-gray-50 to-white rounded-xl hover:from-primary-50 hover:to-white transition-all border border-gray-100"
              >
                <div className="flex items-center gap-3">
                  <div
                    className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-sm"
                    style={{
                      background: "linear-gradient(135deg,#5D4037,#6D4C41)",
                    }}
                  >
                    {employee.first_name?.[0]}
                    {employee.last_name?.[0]}
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900 text-sm">
                      {employee.full_name}
                    </p>
                    <p className="text-xs text-gray-500">{employee.position}</p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-xs font-medium text-gray-700">
                    {employee.department?.name || "—"}
                  </p>
                  <p className="text-xs text-gray-400">
                    {new Date(employee.hire_date).toLocaleDateString()}
                  </p>
                </div>
              </div>
            ))}
            {(!stats?.recent_hires || stats.recent_hires.length === 0) && (
              <div className="text-center py-8 text-gray-400">
                <Users
                  size={40}
                  weight="duotone"
                  className="mx-auto mb-2 opacity-50"
                />
                <p className="text-sm">No recent hires</p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Companies Grid (Super Admin) */}
      {isSuperAdmin() && stats?.recent_companies && (
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
              <Buildings
                size={24}
                className="text-primary-600"
                weight="duotone"
              />
              Subsidiary Companies
            </h3>
            <Link
              to="/companies"
              className="text-xs bg-primary-50 text-primary-600 px-3 py-1 rounded-full font-semibold hover:bg-primary-100"
            >
              Manage All
            </Link>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {stats.recent_companies.map((company) => {
              const healthColors = {
                excellent: "#16a34a",
                good: "#5D4037",
                fair: "#f59e0b",
                poor: "#ef4444",
                critical: "#dc2626",
              };
              const hc = healthColors[company.health_status] || "#6b7280";
              const fmt = (v) =>
                v > 0 ? `₦${Number(v).toLocaleString()}` : "—";
              return (
                <Link
                  key={company.id}
                  to={`/companies/${company.id}`}
                  className="p-5 bg-white rounded-xl border border-gray-100 hover:border-primary-200 hover:shadow-md transition-all group"
                >
                  <div className="flex items-center gap-3 mb-4">
                    <div
                      className="w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold text-base shadow-md flex-shrink-0"
                      style={{
                        background: "linear-gradient(135deg,#5D4037,#6D4C41)",
                      }}
                    >
                      {company.name?.[0]}
                    </div>
                    <div className="flex-1 min-w-0">
                      <h4 className="font-bold text-gray-900 group-hover:text-primary-700 transition-colors truncate">
                        {company.name}
                      </h4>
                      <span
                        className="text-xs font-medium capitalize"
                        style={{ color: hc }}
                      >
                        {company.health_status || "good"}
                      </span>
                    </div>
                    <ArrowRight
                      size={16}
                      className="text-gray-300 group-hover:text-primary-500 flex-shrink-0 transition-colors"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-2 text-xs">
                    <div className="bg-primary-50 rounded-lg p-2">
                      <div className="text-gray-500 mb-0.5">Revenue</div>
                      <div className="font-bold text-gray-900">
                        {fmt(company.revenue)}
                      </div>
                    </div>
                    <div className="bg-red-50 rounded-lg p-2">
                      <div className="text-gray-500 mb-0.5">Expenses</div>
                      <div className="font-bold text-gray-900">
                        {fmt(company.expenses_manual)}
                      </div>
                    </div>
                    <div className="bg-green-50 rounded-lg p-2">
                      <div className="text-gray-500 mb-0.5">Cash</div>
                      <div className="font-bold text-gray-900">
                        {fmt(company.cash_balance)}
                      </div>
                    </div>
                    <div className="bg-purple-50 rounded-lg p-2">
                      <div className="text-gray-500 mb-0.5">Employees</div>
                      <div className="font-bold text-gray-900">
                        {company.employee_count}
                      </div>
                    </div>
                  </div>
                </Link>
              );
            })}
          </div>
        </div>
      )}

      {/* Asset Creation Modal (Super Admin) */}
      {showAssetModal && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50"
          onClick={() => setShowAssetModal(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl w-full max-w-lg"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between p-5 border-b">
              <h3 className="font-bold">Add Holding Asset</h3>
              <button
                onClick={() => setShowAssetModal(false)}
                className="p-1 hover:bg-gray-100 rounded-lg"
              >
                <X size={20} />
              </button>
            </div>
            <form
              className="p-5 space-y-4"
              onSubmit={async (e) => {
                e.preventDefault();
                const fd = new FormData();
                Object.entries(assetForm).forEach(([k, v]) => {
                  if (v !== null && v !== undefined) fd.append(k, v);
                });
                if (assetReceipt) fd.append("receipt", assetReceipt);
                try {
                  await axios.post("/api/company-assets", fd, {
                    headers: { "Content-Type": "multipart/form-data" },
                  });
                  toast.success("Asset added");
                  setShowAssetModal(false);
                  fetchDashboardData();
                } catch (err) {
                  toast.error(
                    err.response?.data?.message || "Failed to add asset",
                  );
                }
              }}
            >
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <Inp
                  label="Name"
                  value={assetForm.name}
                  onChange={(e) =>
                    setAssetForm((p) => ({ ...p, name: e.target.value }))
                  }
                  required
                />
                <Sel
                  label="Category"
                  value={assetForm.category}
                  onChange={(e) =>
                    setAssetForm((p) => ({ ...p, category: e.target.value }))
                  }
                >
                  <option value="real_estate">Real Estate</option>
                  <option value="equipment">Equipment</option>
                  <option value="vehicle">Vehicle</option>
                  <option value="furniture">Furniture</option>
                  <option value="technology">Technology</option>
                  <option value="inventory">Inventory</option>
                  <option value="investment">Investment</option>
                  <option value="intangible">Intangible</option>
                  <option value="other">Other</option>
                </Sel>
                <Inp
                  label="Purchase Value (₦)"
                  type="number"
                  value={assetForm.purchase_value}
                  onChange={(e) =>
                    setAssetForm((p) => ({
                      ...p,
                      purchase_value: e.target.value,
                    }))
                  }
                  required
                />
                <Inp
                  label="Current Value (₦)"
                  type="number"
                  value={assetForm.current_value}
                  onChange={(e) =>
                    setAssetForm((p) => ({
                      ...p,
                      current_value: e.target.value,
                    }))
                  }
                />
                <Inp
                  label="Purchase Date"
                  type="date"
                  value={assetForm.purchase_date}
                  onChange={(e) =>
                    setAssetForm((p) => ({
                      ...p,
                      purchase_date: e.target.value,
                    }))
                  }
                />
                <Inp
                  label="Vendor"
                  value={assetForm.vendor_name}
                  onChange={(e) =>
                    setAssetForm((p) => ({ ...p, vendor_name: e.target.value }))
                  }
                />
                <Inp
                  label="Location"
                  value={assetForm.location}
                  onChange={(e) =>
                    setAssetForm((p) => ({ ...p, location: e.target.value }))
                  }
                />
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">
                    Receipt (pdf/jpg/png)
                  </label>
                  <input
                    type="file"
                    accept=".pdf,.jpg,.jpeg,.png"
                    onChange={(e) => setAssetReceipt(e.target.files[0] || null)}
                  />
                </div>
              </div>
              <div className="flex justify-end gap-2 pt-2">
                <button
                  type="button"
                  onClick={() => setShowAssetModal(false)}
                  className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 bg-green-600 text-white rounded-xl"
                >
                  Add Asset
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Departments Overview (Company User) */}
      {!isSuperAdmin() && stats?.departments_list && (
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
              <Briefcase
                size={24}
                className="text-green-600"
                weight="duotone"
              />
              Departments Overview
            </h3>
            <Link
              to="/departments"
              className="text-xs bg-green-50 text-green-600 px-3 py-1 rounded-full font-semibold hover:bg-green-100"
            >
              View All
            </Link>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {stats.departments_list.map((dept) => (
              <div
                key={dept.id}
                className="p-5 bg-gradient-to-br from-gray-50 to-white rounded-xl border border-gray-100 hover:shadow-md transition-all"
              >
                <div className="flex items-center justify-between mb-3">
                  <h4 className="font-bold text-gray-900">{dept.name}</h4>
                  <span className="bg-primary-100 text-primary-700 px-2 py-1 rounded-lg text-xs font-bold">
                    {dept.employees_count}
                  </span>
                </div>
                <div className="flex items-center gap-2 text-sm text-gray-500">
                  <Users size={14} />
                  <span>Manager: {dept.manager?.name || "Not assigned"}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function KpiCard({
  icon: Icon,
  iconColor,
  title,
  value,
  subtitle,
  trend,
  trendValue,
}) {
  const bgMap = {
    brown: "",
    purple: "bg-purple-500",
    green: "bg-green-500",
    orange: "bg-orange-500",
  };
  const styleMap = { brown: { background: "#5D4037" } };
  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 hover:shadow-md transition-all">
      <div className="flex items-center justify-between">
        <div className="flex-1">
          <p className="text-sm font-medium text-gray-500 mb-1">{title}</p>
          <div className="flex items-baseline gap-2">
            <h3 className="text-3xl font-bold text-gray-900">
              {typeof value === "number" ? value.toLocaleString() : value}
            </h3>
            {trend && (
              <span
                className={`inline-flex items-center gap-1 text-xs font-bold ${trend === "up" ? "text-green-600" : "text-red-600"}`}
              >
                {trend === "up" ? (
                  <ArrowUp size={12} weight="bold" />
                ) : (
                  <ArrowDown size={12} weight="bold" />
                )}
                {trendValue}
              </span>
            )}
          </div>
          <p className="text-xs text-gray-400 mt-2">{subtitle}</p>
        </div>
        <div
          className={`${bgMap[iconColor]} rounded-xl p-3 text-white shadow-lg`}
          style={styleMap[iconColor] || {}}
        >
          <Icon size={28} weight="duotone" />
        </div>
      </div>
    </div>
  );
}
