import React, { useState } from "react";
import { useGetCustomersReportQuery } from "../../features/report/customersAPI";
import {
  BarChart,
  Bar,
  ResponsiveContainer,
  Tooltip,
  XAxis,
} from "recharts";
import { FiUsers, FiChevronDown } from "react-icons/fi";

const CustomersReport = () => {
  const { data, isLoading, isError } = useGetCustomersReportQuery();
  const [activePeriod, setActivePeriod] = useState("weekly");

  if (isLoading) {
    return (
      <div className="p-6 text-center animate-pulse">
        Loading report...
      </div>
    );
  }

  if (isError) {
    return (
      <p className="p-6 text-center text-red-500">
        Error loading data
      </p>
    );
  }

  /* SAFE DATA EXTRACTION */

  const report = data?.data || {};

  const newCustomers = report?.newCustomers || 0;
  const repeatCustomers = report?.repeatCustomers || 0;

  const graph = report?.graph || {};

  const periods = Object.keys(graph);

  const selectedPeriod =
    Array.isArray(graph[activePeriod])
      ? graph[activePeriod]
      : Array.isArray(graph[periods[0]])
      ? graph[periods[0]]
      : [];

  const totalCustomers = newCustomers + repeatCustomers;

  return (
    <div
      className="bg-white rounded-3xl shadow-xl border border-gray-100 p-6"
      style={{ backdropFilter: "blur(12px)" }}
    >
      {/* HEADER */}

      <div className="flex items-center justify-between mb-6">
        <div className="flex items-start gap-4">

          <div
            className="
              w-14 h-14 rounded-2xl
              bg-gradient-to-br from-indigo-500 to-indigo-600
              flex items-center justify-center
              shadow-lg text-white text-2xl
            "
          >
            <FiUsers />
          </div>

          <div>
            <p className="text-sm text-gray-500">
              Total Customers
            </p>

            <h2 className="text-4xl font-extrabold">
              {totalCustomers}
            </h2>

            <div className="flex gap-6 mt-2 text-sm text-gray-600">

              <span>
                <span className="font-semibold text-indigo-600">
                  {newCustomers}
                </span>{" "}
                New
              </span>

              <span>
                <span className="font-semibold text-green-600">
                  {repeatCustomers}
                </span>{" "}
                Repeat
              </span>

            </div>
          </div>
        </div>

        {/* PERIOD SELECT */}

        {periods.length > 0 && (
          <div className="relative">

            <select
              value={activePeriod}
              onChange={(e) =>
                setActivePeriod(e.target.value)
              }
              className="
                appearance-none px-4 py-2 pr-10
                rounded-full border border-gray-200
                shadow-sm focus:outline-none
                focus:ring-2 focus:ring-indigo-500
                text-gray-700 cursor-pointer
              "
            >
              {periods.map((period) => (
                <option key={period} value={period}>
                  {period.charAt(0).toUpperCase() +
                    period.slice(1)}
                </option>
              ))}
            </select>

            <FiChevronDown
              className="
                absolute right-3 top-1/2
                -translate-y-1/2 text-gray-400
                pointer-events-none
              "
            />

          </div>
        )}
      </div>

      {/* CHART */}

      <div className="w-full h-[240px] min-h-[240px]">

        <ResponsiveContainer width="100%" height="100%">

          <BarChart data={selectedPeriod}>

            <XAxis
              dataKey="label"
              tick={{ fontSize: 12 }}
            />

            <Tooltip
              cursor={{ opacity: 0.2 }}
              contentStyle={{
                borderRadius: "10px",
                border: "none",
                boxShadow:
                  "0 4px 16px rgba(0,0,0,0.1)",
              }}
            />

            <defs>
              <linearGradient
                id="softGreen"
                x1="0"
                y1="0"
                x2="0"
                y2="1"
              >
                <stop
                  offset="0%"
                  stopColor="#34d399"
                  stopOpacity="0.95"
                />
                <stop
                  offset="100%"
                  stopColor="#34d399"
                  stopOpacity="0.3"
                />
              </linearGradient>
            </defs>

            <Bar
              dataKey="value"
              fill="url(#softGreen)"
              radius={[10, 10, 0, 0]}
              barSize={28}
            />

          </BarChart>

        </ResponsiveContainer>

      </div>
    </div>
  );
};

export default CustomersReport;