import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "../../context/AuthContext.jsx";
import { formatPermitValidity, usePermitValidity } from "../../context/PermitValidityContext.jsx";
import PageHeader from "../../components/common/PageHeader.jsx";
import ErrorBanner from "../../components/common/ErrorBanner.jsx";
import DashboardPermitCards from "../../components/dashboard/DashboardPermitCards.jsx";
import DashboardRecentActivity from "../../components/dashboard/DashboardRecentActivity.jsx";
import PermitBarChart from "../../components/dashboard/PermitBarChart.jsx";
import PermitTrendChart from "../../components/dashboard/PermitTrendChart.jsx";
import { getDashboardStats } from "../../services/dashboardApi.js";
import "../../styles/ptw-dashboard.css";

function IconForm() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <path d="M14 2v6h6M16 13H8M16 17H8M10 9H8" />
    </svg>
  );
}

function IconPermit() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
      <path d="M4 8h16v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8z" />
      <path d="M8 8V6a4 4 0 1 1 8 0v2" />
    </svg>
  );
}

function IconArrow() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
      <path d="M5 12h14M13 6l6 6-6 6" />
    </svg>
  );
}

function QuickActionCard({ icon, title, description, onClick, primary }) {
  return (
    <button
      type="button"
      className={`ptw-dash-quick__action${primary ? " ptw-dash-quick__action--primary" : ""}`}
      onClick={onClick}
    >
      <span className="ptw-dash-quick__icon" aria-hidden>{icon}</span>
      <span className="ptw-dash-quick__text">
        <strong>{title}</strong>
        <span>{description}</span>
      </span>
      <span className="ptw-dash-quick__arrow" aria-hidden>
        <IconArrow />
      </span>
    </button>
  );
}

const QUICK_ACTIONS = [
  {
    id: "fill-form",
    title: "Fill permit form",
    description: "Start a new Permit to Work",
    icon: <IconForm />,
    primary: true
  },
  {
    id: "permits-submissions",
    title: "Permits & submissions",
    description: "Review lifecycle and validity",
    icon: <IconPermit />
  },
  {
    id: "permit-preview",
    title: "Submitted forms",
    description: "Preview saved answers",
    icon: <IconPermit />
  }
];

export default function AdminOverviewPage({ onNavigate }) {
  const { auth } = useAuth();
  const { activePermit } = usePermitValidity();
  const [dashboard, setDashboard] = useState(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);
  const [refreshSignal, setRefreshSignal] = useState(0);

  const loadDashboard = useCallback(async ({ refreshTrend = false } = {}) => {
    setLoading(true);
    setError("");
    try {
      const data = await getDashboardStats("all");
      setDashboard(data);
      if (refreshTrend) {
        setRefreshSignal((count) => count + 1);
      }
    } catch (err) {
      setError(err?.response?.data?.message || err.message);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const greeting = useMemo(() => {
    const hour = new Date().getHours();
    if (hour < 12) return "Good morning";
    if (hour < 17) return "Good afternoon";
    return "Good evening";
  }, []);

  const userName = auth?.user?.employee_name || "Admin";
  const todayLabel = useMemo(
    () =>
      new Date().toLocaleDateString(undefined, {
        weekday: "long",
        month: "long",
        day: "numeric"
      }),
    []
  );

  const goToPermits = useCallback(
    (options = {}) => {
      onNavigate?.("permits-submissions", options);
    },
    [onNavigate]
  );

  const goToPermitPreview = useCallback(
    (permitId) => {
      if (!permitId) {
        onNavigate?.("permit-preview");
        return;
      }
      onNavigate?.("permit-preview", { permitId });
    },
    [onNavigate]
  );

  return (
    <div className="portal-page ptw-overview-page">
      <PageHeader
        title="Dashboard"
        subtitle="Permit analytics, trends, and recent activity."
        actions={(
          <button
            type="button"
            className="swi-btn swi-btn--ghost"
            onClick={() => loadDashboard({ refreshTrend: true })}
            disabled={loading}
          >
            {loading ? "Refreshing…" : "Refresh"}
          </button>
        )}
      />
      <ErrorBanner message={error} />

      <section className="ptw-dash-welcome" aria-label="Welcome">
        <div className="ptw-dash-welcome__main">
          <p className="ptw-dash-welcome__date">{todayLabel}</p>
          <h2 className="ptw-dash-welcome__title">
            {greeting}, {userName.split(/\s+/)[0]}
          </h2>
          <p className="ptw-dash-welcome__lead">
            Track permits by location, job type, and status.
            {dashboard?.user?.location_name ? (
              <>
                {" "}
                Your location: <strong>{dashboard.user.location_name}</strong>.
              </>
            ) : null}
          </p>
          <button
            type="button"
            className="swi-btn swi-btn--primary ptw-dash-welcome__cta"
            onClick={() => onNavigate?.("fill-form")}
          >
            Start new permit
          </button>
        </div>
        {activePermit ? (
          <button
            type="button"
            className="ptw-dash-welcome__aside ptw-dash-welcome__aside--clickable"
            aria-label="Open active permit"
            onClick={() => goToPermitPreview(activePermit.permitId)}
          >
            <span className="ptw-dash-welcome__aside-badge">Active now</span>
            <strong>{activePermit.permitNumber || `Permit #${activePermit.permitId}`}</strong>
            <span className="ptw-dash-welcome__aside-meta">
              Expires {formatPermitValidity(activePermit.validUntil)}
            </span>
          </button>
        ) : null}
      </section>

      <DashboardPermitCards
        cards={dashboard?.cards}
        userLocationName={dashboard?.user?.location_name}
        loading={loading}
        onCardClick={(target) =>
          goToPermits(target?.dashFilter ? { dashFilter: target.dashFilter } : {})
        }
      />

      <PermitTrendChart refreshSignal={refreshSignal} onNavigate={onNavigate} />

      <section className="ptw-dash-section" aria-label="Permit distribution">
        <h2 className="ptw-dash-section__label">Breakdown</h2>
        <div className="ptw-dash-charts-grid">
          <PermitBarChart
            data={dashboard?.location_wise || []}
            title="Location-wise permits"
            description="Permit count by plant / site location."
            emptyMessage="No location data yet."
            onClick={() => goToPermits({ dashFilter: "location" })}
            onBarClick={() => goToPermits({ dashFilter: "location" })}
          />
          <PermitBarChart
            data={dashboard?.job_type_wise || []}
            title="Job type permits"
            description="Specialized permit submissions (excluding General, Handover, and Handback)."
            emptyMessage="No specialized job type submissions yet."
            onClick={() => goToPermits()}
            onBarClick={(item) =>
              goToPermits(item?.label ? { dashJobType: item.label } : {})
            }
          />
        </div>
      </section>

      <section className="ptw-dash-section" aria-label="Activity and shortcuts">
        <h2 className="ptw-dash-section__label">Workspace</h2>
        <div className="ptw-dash-bottom-grid">
          <DashboardRecentActivity
            items={dashboard?.recent_activity || []}
            loading={loading}
            onPermitClick={goToPermitPreview}
            onViewAll={() => goToPermits()}
          />

          <section className="ptw-dash-shell ptw-dash-quick" aria-label="Quick actions">
            <header className="ptw-dash-shell__head">
              <div className="ptw-dash-shell__intro">
                <p className="ptw-dash-shell__eyebrow">Shortcuts</p>
                <h3 className="ptw-dash-shell__title">Quick actions</h3>
                <p className="ptw-dash-shell__desc">
                  Jump straight to common permit tasks.
                </p>
              </div>
            </header>
            <div className="ptw-dash-shell__body">
              <div className="ptw-dash-quick__grid">
                {QUICK_ACTIONS.map((action) => (
                  <QuickActionCard
                    key={action.id}
                    icon={action.icon}
                    title={action.title}
                    description={action.description}
                    primary={action.primary}
                    onClick={() => onNavigate(action.id)}
                  />
                ))}
              </div>
            </div>
          </section>
        </div>
      </section>
    </div>
  );
}
