import React from "react";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import {
  PieChart,
  Pie,
  Cell,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  CartesianGrid,
  ResponsiveContainer,
  Legend,
} from "recharts";

const statusMeta = {
  DELIVERED: { icon: "✅", bg: "bg-green-50", border: "border-green-200", text: "text-green-700", badge: "bg-green-100 text-green-700" },
  PENDING:   { icon: "⏳", bg: "bg-yellow-50", border: "border-yellow-200", text: "text-yellow-700", badge: "bg-yellow-100 text-yellow-700" },
  SHIPPED:   { icon: "🚚", bg: "bg-blue-50", border: "border-blue-200", text: "text-blue-700", badge: "bg-blue-100 text-blue-700" },
  CANCELLED: { icon: "❌", bg: "bg-red-50", border: "border-red-200", text: "text-red-700", badge: "bg-red-100 text-red-700" },
  PROCESSING:{ icon: "⚙️", bg: "bg-purple-50", border: "border-purple-200", text: "text-purple-700", badge: "bg-purple-100 text-purple-700" },
};

const CustomTooltip = ({ active, payload }) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-white border border-gray-200 rounded-xl p-3 shadow-lg">
        <p className="font-bold text-gray-900">{payload[0].name}</p>
        <p className="text-gray-600">Count: <span className="font-bold text-[#704F38]">{payload[0].value}</span></p>
      </div>
    );
  }
  return null;
};

const OrdersByStatusPage = () => {
  const navigate = useNavigate();
  const { stats } = useSelector((state) => state.dashboard);

  const ordersByStatus = stats?.charts?.ordersByStatus || [];
  const total = ordersByStatus.reduce((sum, s) => sum + s.count, 0);

  if (!stats) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <p className="text-gray-500 text-xl">No data available</p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 p-6">
      <div className="max-w-6xl mx-auto space-y-8">

        {/* Header */}
        <div className="flex items-center gap-4">
          <button
            onClick={() => navigate(-1)}
            className="flex items-center gap-2 text-gray-600 hover:text-[#704F38] transition-colors font-medium"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
            Back
          </button>
          <div className="h-6 w-px bg-gray-300" />
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Orders by Status</h1>
            <p className="text-gray-500 text-sm">Detailed breakdown of all {total} orders</p>
          </div>
        </div>

        {/* Summary Cards */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
          {ordersByStatus.map((status) => {
            const meta = statusMeta[status.label] || {
              icon: "📦", bg: "bg-gray-50", border: "border-gray-200",
              text: "text-gray-700", badge: "bg-gray-100 text-gray-700",
            };
            const percentage = total > 0 ? ((status.count / total) * 100).toFixed(1) : 0;

            return (
              <div
                key={status.label}
                className={`${meta.bg} ${meta.border} border-2 rounded-2xl p-5 flex flex-col gap-3`}
              >
                <div className="flex items-center justify-between">
                  <span className="text-2xl">{meta.icon}</span>
                  <span className={`text-xs font-bold px-2 py-1 rounded-full ${meta.badge}`}>
                    {percentage}%
                  </span>
                </div>
                <div>
                  <p className={`text-3xl font-extrabold ${meta.text}`}>{status.count}</p>
                  <p className="text-sm text-gray-600 font-medium mt-1">{status.label}</p>
                </div>
                {/* Mini progress bar */}
                <div className="w-full bg-white rounded-full h-1.5">
                  <div
                    className="h-1.5 rounded-full transition-all duration-700"
                    style={{ width: `${percentage}%`, backgroundColor: status.color }}
                  />
                </div>
              </div>
            );
          })}
        </div>

        {/* Charts Row */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Pie Chart */}
          <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6">
            <h2 className="text-lg font-bold text-gray-900 mb-6">Distribution Overview</h2>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={ordersByStatus}
                  cx="50%"
                  cy="50%"
                  innerRadius={70}
                  outerRadius={110}
                  paddingAngle={4}
                  dataKey="count"
                >
                  {ordersByStatus.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip content={<CustomTooltip />} />
                <Legend
                  formatter={(value) => <span className="text-sm text-gray-700">{value}</span>}
                />
              </PieChart>
            </ResponsiveContainer>

            {/* Total in center label */}
            <div className="text-center mt-2">
              <p className="text-sm text-gray-500">Total Orders</p>
              <p className="text-3xl font-extrabold text-[#704F38]">{total}</p>
            </div>
          </div>

          {/* Bar Chart */}
          <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6">
            <h2 className="text-lg font-bold text-gray-900 mb-6">Status Comparison</h2>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={ordersByStatus} barSize={40}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis
                  dataKey="label"
                  stroke="#888"
                  style={{ fontSize: "11px" }}
                  tick={{ fill: "#6b7280" }}
                />
                <YAxis stroke="#888" style={{ fontSize: "12px" }} />
                <Tooltip content={<CustomTooltip />} />
                <Bar dataKey="count" name="Orders" radius={[6, 6, 0, 0]}>
                  {ordersByStatus.map((entry, index) => (
                    <Cell key={`bar-${index}`} fill={entry.color} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Detailed Table */}
        <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
          <div className="bg-gradient-to-r from-[#704F38] to-[#8d6449] px-6 py-4">
            <h2 className="text-lg font-bold text-white">Status Summary Table</h2>
          </div>
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-200">
                <th className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Status</th>
                <th className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Order Count</th>
                <th className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Percentage</th>
                <th className="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">Progress</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {ordersByStatus.map((status) => {
                const percentage = total > 0 ? ((status.count / total) * 100).toFixed(1) : 0;
                const meta = statusMeta[status.label] || { badge: "bg-gray-100 text-gray-700" };
                return (
                  <tr key={status.label} className="hover:bg-gray-50 transition-colors">
                    <td className="px-6 py-4">
                      <span className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-bold ${meta.badge}`}>
                        <span className="w-2 h-2 rounded-full" style={{ backgroundColor: status.color }} />
                        {status.label}
                      </span>
                    </td>
                    <td className="px-6 py-4 font-bold text-gray-900 text-lg">{status.count}</td>
                    <td className="px-6 py-4 font-semibold text-gray-700">{percentage}%</td>
                    <td className="px-6 py-4 w-48">
                      <div className="w-full bg-gray-100 rounded-full h-2">
                        <div
                          className="h-2 rounded-full transition-all duration-700"
                          style={{ width: `${percentage}%`, backgroundColor: status.color }}
                        />
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
            <tfoot>
              <tr className="bg-gray-50 border-t-2 border-gray-200">
                <td className="px-6 py-4 font-bold text-gray-900">Total</td>
                <td className="px-6 py-4 font-extrabold text-[#704F38] text-lg">{total}</td>
                <td className="px-6 py-4 font-bold text-gray-700">100%</td>
                <td className="px-6 py-4" />
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>
  );
};

export default OrdersByStatusPage;