"use client";

import { useState, useEffect } from "react";
import {
  getLeadGrade,
  LEAD_GRADE_COLORS,
  type LeadGrade,
} from "@/lib/types/lead-crm.types";
import type { LeadOutput, ScoringRuleOutput } from "@/lib/types/lead-crm.types";

interface ScoringDashboardProps {
  isAr: boolean;
  leads: LeadOutput[];
  scoringRules: ScoringRuleOutput[];
}

interface GradeDistribution {
  grade: LeadGrade;
  count: number;
  percentage: number;
}

export default function ScoringDashboard({
  isAr,
  leads,
  scoringRules,
}: ScoringDashboardProps) {
  const [distribution, setDistribution] = useState<GradeDistribution[]>([]);
  const [avgScore, setAvgScore] = useState(0);

  useEffect(() => {
    if (leads.length === 0) {
      setDistribution([]);
      setAvgScore(0);
      return;
    }

    const grades: LeadGrade[] = ["A", "B", "C", "D", "F"];
    const counts: Record<string, number> = { A: 0, B: 0, C: 0, D: 0, F: 0 };
    let totalScore = 0;

    for (const lead of leads) {
      const grade = getLeadGrade(lead.score);
      counts[grade]++;
      totalScore += lead.score;
    }

    setDistribution(
      grades.map((g) => ({
        grade: g,
        count: counts[g],
        percentage: leads.length > 0 ? (counts[g] / leads.length) * 100 : 0,
      })),
    );
    setAvgScore(Math.round(totalScore / leads.length));
  }, [leads]);

  const gradeLabels: Record<LeadGrade, { en: string; ar: string }> = {
    A: { en: "Hot", ar: "ساخن" },
    B: { en: "Warm", ar: "دافئ" },
    C: { en: "Neutral", ar: "محايد" },
    D: { en: "Cool", ar: "بارد" },
    F: { en: "Cold", ar: "بارد جداً" },
  };

  return (
    <div className="space-y-6">
      <div>
        <h3 className="text-lg font-bold text-slate-900">
          {isAr ? "لوحة النقاط" : "Scoring Dashboard"}
        </h3>
        <p className="text-sm text-slate-500">
          {isAr
            ? "توزيع درجات العملاء المحتملين"
            : "Lead score distribution and grade breakdown"}
        </p>
      </div>

      {/* Summary cards */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <div className="bg-white rounded-2xl border border-slate-200 p-4">
          <p className="text-xs text-slate-500">
            {isAr ? "إجمالي العملاء" : "Total Leads"}
          </p>
          <p className="text-2xl font-bold text-slate-900 mt-1">
            {leads.length}
          </p>
        </div>
        <div className="bg-white rounded-2xl border border-slate-200 p-4">
          <p className="text-xs text-slate-500">
            {isAr ? "متوسط النقاط" : "Avg Score"}
          </p>
          <p className="text-2xl font-bold text-slate-900 mt-1">{avgScore}</p>
        </div>
        <div className="bg-white rounded-2xl border border-slate-200 p-4">
          <p className="text-xs text-slate-500">
            {isAr ? "قواعد نشطة" : "Active Rules"}
          </p>
          <p className="text-2xl font-bold text-slate-900 mt-1">
            {scoringRules.filter((r) => r.isActive).length}
          </p>
        </div>
        <div className="bg-white rounded-2xl border border-slate-200 p-4">
          <p className="text-xs text-slate-500">
            {isAr ? "عملاء ساخنين" : "Hot Leads (A)"}
          </p>
          <p className="text-2xl font-bold text-emerald-600 mt-1">
            {distribution.find((d) => d.grade === "A")?.count || 0}
          </p>
        </div>
      </div>

      {/* Grade distribution */}
      <div className="bg-white rounded-2xl border border-slate-200 p-5">
        <h4 className="text-sm font-semibold text-slate-900 mb-4">
          {isAr ? "توزيع الدرجات" : "Grade Distribution"}
        </h4>
        {leads.length === 0 ? (
          <p className="text-sm text-slate-400 text-center py-8">
            {isAr ? "لا توجد بيانات" : "No data available"}
          </p>
        ) : (
          <div className="space-y-3">
            {distribution.map((item) => {
              const colors = LEAD_GRADE_COLORS[item.grade];
              return (
                <div key={item.grade} className="flex items-center gap-3">
                  <div
                    className={`w-8 h-8 rounded-full ${colors.bg} ${colors.text} border ${colors.border} flex items-center justify-center font-bold text-sm flex-shrink-0`}
                  >
                    {item.grade}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-medium text-slate-700">
                        {isAr
                          ? gradeLabels[item.grade].ar
                          : gradeLabels[item.grade].en}
                      </span>
                      <span className="text-xs text-slate-500">
                        {item.count} ({Math.round(item.percentage)}%)
                      </span>
                    </div>
                    <div className="h-2 bg-slate-100 rounded-full overflow-hidden">
                      <div
                        className={`h-full rounded-full transition-all ${
                          item.grade === "A"
                            ? "bg-emerald-500"
                            : item.grade === "B"
                              ? "bg-blue-500"
                              : item.grade === "C"
                                ? "bg-amber-500"
                                : item.grade === "D"
                                  ? "bg-orange-500"
                                  : "bg-red-500"
                        }`}
                        style={{ width: `${item.percentage}%` }}
                      />
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Score ranges reference */}
      <div className="bg-white rounded-2xl border border-slate-200 p-5">
        <h4 className="text-sm font-semibold text-slate-900 mb-3">
          {isAr ? "نطاقات الدرجات" : "Score Ranges"}
        </h4>
        <div className="grid grid-cols-5 gap-2 text-center text-xs">
          {[
            { grade: "A" as LeadGrade, range: "80-100" },
            { grade: "B" as LeadGrade, range: "60-79" },
            { grade: "C" as LeadGrade, range: "40-59" },
            { grade: "D" as LeadGrade, range: "20-39" },
            { grade: "F" as LeadGrade, range: "0-19" },
          ].map(({ grade, range }) => {
            const colors = LEAD_GRADE_COLORS[grade];
            return (
              <div
                key={grade}
                className={`p-2 rounded-xl ${colors.bg} ${colors.text}`}
              >
                <p className="font-bold text-lg">{grade}</p>
                <p className="opacity-80">{range}</p>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
