"use client";

import React, { useMemo } from "react";
import type { JobRow } from "@/lib/api/types/job.types";

interface Props { jobs: JobRow[]; stageFilter?: string; }

export default function JobAnalytics({ jobs, stageFilter }: Props) {
  const filtered = useMemo(() => stageFilter && stageFilter !== "all" ? jobs.filter((j) => j.stage === stageFilter) : jobs, [jobs, stageFilter]);

  const byStage = ["Stage 1", "Stage 2"].map((name) => ({ name, count: filtered.filter((j) => j.stage === name).length }));
  const byRisk  = ["Low", "Medium", "High"].map((name) => ({ name, count: filtered.filter((j) => j.mdRisk === name).length }));

  const RISK_COLORS: Record<string, string> = { Low: "#059669", Medium: "#d97706", High: "#dc2626" };
  const STAGE_COLORS: Record<string, string> = { "Stage 1": "#2563eb", "Stage 2": "#7c3aed" };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px", marginBottom: "20px" }}>
      <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "12px", padding: "18px" }}>
        <h3 style={{ fontSize: "13px", fontWeight: 700, color: "#374151", marginBottom: "14px" }}>By Stage</h3>
        {byStage.map((s) => (
          <div key={s.name} style={{ marginBottom: "10px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", marginBottom: "3px" }}>
              <span style={{ color: "#374151" }}>{s.name}</span>
              <span style={{ color: STAGE_COLORS[s.name], fontWeight: 700 }}>{s.count}</span>
            </div>
            <div style={{ height: "5px", borderRadius: "3px", backgroundColor: "#f3f4f6" }}>
              <div style={{ height: "100%", borderRadius: "3px", backgroundColor: STAGE_COLORS[s.name], width: `${filtered.length ? (s.count / filtered.length) * 100 : 0}%`, transition: "width 0.4s" }} />
            </div>
          </div>
        ))}
      </div>
      <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "12px", padding: "18px" }}>
        <h3 style={{ fontSize: "13px", fontWeight: 700, color: "#374151", marginBottom: "14px" }}>By Risk</h3>
        {byRisk.map((r) => (
          <div key={r.name} style={{ marginBottom: "10px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", marginBottom: "3px" }}>
              <span style={{ color: "#374151" }}>{r.name}</span>
              <span style={{ color: RISK_COLORS[r.name], fontWeight: 700 }}>{r.count}</span>
            </div>
            <div style={{ height: "5px", borderRadius: "3px", backgroundColor: "#f3f4f6" }}>
              <div style={{ height: "100%", borderRadius: "3px", backgroundColor: RISK_COLORS[r.name], width: `${filtered.length ? (r.count / filtered.length) * 100 : 0}%`, transition: "width 0.4s" }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
