'use client';

import { routes } from '@/config/routes';
import TableLayout from '../../table-layout';
import { PiArrowCounterClockwise, PiCalendarBlank, PiChartBar, PiCheckCircle, PiFaders, PiFloppyDisk, PiInfo, PiLightbulb, PiUsers, PiXCircle } from 'react-icons/pi';
import ViewToggle from '@/components/common/ViewToggle';
import { useCallback, useState } from 'react';

type AlertType = 'save' | 'reset' | null;

interface PipelineStage {
  label: string;
  points: number;
  max: number;
  min: number;
}

interface Lead {
  id: number;
  name: string;
  company: string;
  stage: keyof typeof STAGE_POINTS_MAP;
  logs: number;
  prevScore: number;
}

const pageHeader = {
  title: 'Scoring Metrics',
  breadcrumb: [
    { href: routes.dashboard, name: 'Home' },
    { name: 'Lead Management' },
  ],
};


// ── Constants ──────────────────────────────────────────────────────────
const STAGE_POINTS_MAP: Record<string, number> = {
  New: 15,
  Contacted: 30,
  Qualified: 50,
  Proposal: 52,
  Negotiation: 55,
  'Closed Won': 60,
  'Closed Lost': 0,
};

const DEFAULT_STAGES: PipelineStage[] = [
  { label: 'New', points: 15, max: 60, min: 0 },
  { label: 'Contacted', points: 30, max: 60, min: 0 },
  { label: 'Qualified', points: 50, max: 60, min: 0 },
  { label: 'Proposal', points: 52, max: 60, min: 0 },
  { label: 'Negotiation', points: 55, max: 60, min: 0 },
  { label: 'Closed Won', points: 60, max: 60, min: 0 },
  { label: 'Closed Lost', points: 0, max: 60, min: 0 },
];

const SAMPLE_LEADS: Lead[] = [
  { id: 1, name: 'Rajesh Koothrappali', company: 'TechMahindra (New)', stage: 'New', logs: 4, prevScore: 27 },
  { id: 2, name: 'Anjali Menon', company: 'Infosys (Contacted)', stage: 'Contacted', logs: 4, prevScore: 42 },
  { id: 3, name: 'Vikram Malhotra', company: 'Reliance Industries (Proposal)', stage: 'Proposal', logs: 4, prevScore: 64 },
  { id: 4, name: 'Priya Desai', company: 'Tata Consultancy (Negotiation)', stage: 'Negotiation', logs: 4, prevScore: 67 },
];

function RangeSlider({ value, min, max, onChange }: {
  value: number; min: number; max: number; onChange: (v: number) => void;
}) {
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div className="relative w-full h-5 flex items-center">
      <div className="absolute w-full h-1.5 rounded-full bg-gray-200" />
      <div className="absolute h-1.5 rounded-full bg-gray-200" style={{ width: `${pct}%` }} />
      <input
        type="range" min={min} max={max} value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className="absolute w-full opacity-0 cursor-pointer h-5 z-10"
      />
      <div
        className="absolute w-4 h-4 rounded-full bg-primary border-2 border-white shadow-md pointer-events-none"
        style={{ left: `calc(${pct}% - 8px)` }}
      />
    </div>
  );
}

// ── Score bar ──────────────────────────────────────────────────────────
function ScoreBar({ pct, color }: { pct: number; color: string }) {
  return (
    <div className="w-full h-1.5 rounded-full bg-gray-200 overflow-hidden">
      <div
        className="h-full rounded-full transition-all duration-500"
        style={{ width: `${pct}%`, backgroundColor: color }}
      />
    </div>
  );
}

export default function Page() {
  const [stages, setStages] = useState<PipelineStage[]>(DEFAULT_STAGES);
  const [pointsPerLog, setPointsPerLog] = useState(17);
  const [scoreCap, setScoreCap] = useState(12);
  const [alert, setAlert] = useState<AlertType>(null);

  const showAlert = (type: AlertType) => {
    setAlert(type);
    setTimeout(() => setAlert(null), 4000);
  };

  const updateStage = useCallback((idx: number, val: number) => {
    setStages((prev) => prev.map((s, i) => (i === idx ? { ...s, points: val } : s)));
  }, []);

  const reset = () => {
    setStages(DEFAULT_STAGES);
    setPointsPerLog(17);
    setScoreCap(12);
    showAlert('reset');
  };

  const save = () => {
    showAlert('save');
  };

  // Compute live scores
  const computeScore = (lead: Lead) => {
    const stage = stages.find((s) => s.label === lead.stage);
    const statusPts = stage ? stage.points : 0;
    const logPts = Math.min(lead.logs * pointsPerLog, scoreCap);
    return { statusPts, logPts, total: statusPts + logPts };
  };

  const maxPossible = 60 + scoreCap;
  return (
    <>
      <TableLayout
        title={pageHeader.title}
        breadcrumb={pageHeader.breadcrumb}
        data={[]}
        fileName="manaeg_lead"
        header="Module,Add,Edit,Delete,View"
        showExport={false}
        showImport={false}
        actions={
          <ViewToggle
            views={[
              {
                label: 'Manage Lead',
                path: '/manage_lead',
                matchPaths: ['/manage_lead', '/lead_kanban_board'],
                icon: PiUsers,
              },
              {
                label: 'Followup Lead',
                path: '/followup_lead',
                matchPaths: ['/followup_lead', '/followup_kanban_board'],
                icon: PiCalendarBlank,
              },
              {
                label: 'Scoring Metrics',
                path: '/lead_scoring',
                matchPaths: ['/lead_scoring'],
                icon: PiFaders,
              },
            ]}
          />
        }
      >
        <div className="space-y-6">
          <div className="grid grid-cols-12 gap-5 items-start">
            <div className="col-span-9 min-w-0 space-y-4">
              <div
                className={`overflow-hidden transition-all duration-500 ease-in-out ${
                  alert ? 'max-h-16 opacity-100' : 'max-h-0 opacity-0'
                }`}
              >
                {alert === 'save' && (
                  <div className="flex items-center gap-2.5 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-lg px-4 py-2.5">
                    <PiCheckCircle size={18} className="text-emerald-500 flex-shrink-0" />
                    <span className="text-sm font-medium">
                      Successfully saved and recalculated scores for all leads.
                    </span>
                  </div>
                )}
                {alert === 'reset' && (
                  <div className="flex items-center gap-2.5 bg-red-50 border border-red-200 text-red-700 rounded-lg px-4 py-2.5">
                    <PiXCircle size={18} className="text-red-500 flex-shrink-0" />
                    <span className="text-sm font-medium">
                      Successfully restored all settings to default values.
                    </span>
                  </div>
                )}
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="border border-gray-200 rounded-xl p-5 bg-white shadow-sm">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-bold tracking-widest text-black uppercase">
                      % 1. Pipeline Status Weights (Max 60 pts)
                    </span>
                  </div>
                  <p className="text-xs text-gray-400 mb-4">
                    Assign higher score allocation to leads further down the pipeline.
                  </p>
                  <div className="space-y-4">
                    {stages.map((s, i) => (
                      <div key={s.label}>
                        <div className="flex justify-between items-center">
                          <span className="text-sm text-gray-700 font-medium">{s.label}</span>
                          <span className="text-sm font-semibold text-primary">{s.points} pts</span>
                        </div>
                        <RangeSlider
                          value={s.points}
                          min={s.min}
                          max={s.max}
                          onChange={(v) => updateStage(i, v)}
                        />
                      </div>
                    ))}
                  </div>
                </div>
                <div className="border border-gray-200 rounded-xl p-5 bg-white shadow-sm flex flex-col justify-between">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <PiInfo className="text-gray-700" size={14} />
                      <span className="text-xs font-bold tracking-widest text-black uppercase">
                        2. Activity Log Engagement (Max 40 pts)
                      </span>
                    </div>
                    <p className="text-xs text-gray-400 mb-5">
                      Reward sales reps who log regular client events, letters, calls, and transcripts.
                    </p>
                    <div className="space-y-5">
                      <div>
                        <div className="flex justify-between items-center">
                          <span className="text-sm text-gray-700">Points per logged Action/Note</span>
                          <span className="text-sm font-semibold text-primary">+{pointsPerLog} pts / activity</span>
                        </div>
                        <RangeSlider value={pointsPerLog} min={0} max={40} onChange={setPointsPerLog} />
                      </div>
                      <div>
                        <div className="flex justify-between items-center">
                          <span className="text-sm text-gray-700">Engagement Score Cap</span>
                          <span className="text-sm font-semibold text-primary">Max {scoreCap} points</span>
                        </div>
                        <RangeSlider value={scoreCap} min={0} max={40} onChange={setScoreCap} />
                      </div>
                    </div>
                  </div>

                  <div className="mt-6 bg-blue-50 border border-blue-100 rounded-lg px-4 py-3">
                    <div className="flex items-center gap-1.5 mb-1">
                      <PiLightbulb className="text-yellow-500" size={14} />
                      <span className="text-xs font-semibold text-gray-700">Dynamic Scoring Formula:</span>
                    </div>
                    <p className="text-xs text-gray-500 mb-1">Your total Lead Score is calculated as an additive function:</p>
                    <p className="text-xs font-medium text-blue-600">
                      Pipeline Status Points + min(Logged Notes × Points Per Note, Score Cap)
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex justify-end gap-2">
                <button
                  onClick={reset}
                  className="flex items-center gap-1.5 text-xs font-medium text-gray-600 border border-gray-300 rounded-lg px-3 py-1.5 hover:bg-gray-50 transition"
                >
                  <PiArrowCounterClockwise size={14} />
                  Reset to Defaults
                </button>
                <button className="flex items-center gap-2 bg-primary text-white text-sm font-semibold px-6 py-2.5 rounded-xl shadow transition">
                  <PiFloppyDisk size={16} />
                  Save &amp; Recalculate Live Scores
                </button>
              </div>
            </div>
            <div className="col-span-3 border border-gray-200 rounded-xl bg-white shadow-sm overflow-hidden">
              <div className="bg-blue-50 border-b border-blue-100 px-4 py-3">
                <div className="flex items-center gap-2">
                  <PiChartBar className="text-primary" size={16} />
                  <span className="text-xs font-bold tracking-widest text-primary uppercase">
                    Live Scoring Simulator
                  </span>
                </div>
                <span className="text-xs text-gray-500 mt-0.5">
                  Real-time simulation of lead scores as you adjust weights.
                </span>
              </div>

              <div className="max-h-96 overflow-y-auto p-3">
                {SAMPLE_LEADS.map((lead) => {
                  const { statusPts, logPts, total } = computeScore(lead);
                  const pct = Math.min((total / maxPossible) * 100, 100);
                  const barColor = pct >= 60 ? '#06437F' : pct >= 40 ? '#198cff' : 'rgb(188, 220, 255)';
                  
                  return (
                    <div key={lead.id} className="px-2 py-3 rounded-lg bg-gray-50 mb-3 border border-gray-100">
                      <div className="flex justify-between items-start mb-0.5">
                        <span className="text-sm font-bold text-gray-800">{lead.name}</span>
                        <div className="flex items-center gap-1">
                          <span className="text-xs text-gray-400 line-through">{lead.prevScore}%</span>
                          <span className="text-sm font-bold text-primary">{Math.round(pct)}%</span>
                        </div>
                      </div>
                      <p className="text-xs text-gray-400 mb-2">{lead.company}</p>
                      <ScoreBar pct={pct} color={barColor} />
                      <div className="grid grid-cols-2 text-center mt-2">
                        <div className='flex flex-col'>
                          <span className="text-[10px] text-gray-400 uppercase tracking-wider">Status</span>
                          <span className="text-lg font-semibold text-gray-700">+{statusPts}</span>
                        </div>
                        <div className='flex flex-col'>
                          <span className="text-[10px] text-gray-400 uppercase tracking-wider">Logs</span>
                          <span className="text-lg font-semibold text-violet-600">+{logPts}</span>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>

              <div className="border-t border-gray-100 bg-blue-50 px-4 py-3">
                <div className="flex items-start gap-1.5">
                  <PiInfo className="text-blue-400 mt-0.5 flex-shrink-0" size={13} />
                  <p className="text-[11px] text-gray-500 leading-relaxed">
                    <span className="font-semibold text-gray-600">Deterministic Rules:</span>{' '}
                    Calculations occur in real-time. Slide any metrics on the left, and check live variance output simulations instantly!
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </TableLayout>
    </>
  );
}