'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { StatCardSkeleton } from '@/components/Skeletons';
import Modal from '@/components/Modal';

type Target = { id: number; periodMonth: string; targetTzs: string; achievedTzs: string; employee: { id: number; name: string } };
type Commission = { id: number; periodMonth: string; amountTzs: string; basis: string | null; employee: { name: string } };
type EmployeeOption = { id: number; name: string };

function currentMonth() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}

export default function SalesTargetsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [targets, setTargets] = useState<Target[]>([]);
  const [commissions, setCommissions] = useState<Commission[]>([]);
  const [leaderboard, setLeaderboard] = useState<{ employee: string; achievedTzs: number }[]>([]);
  const [employees, setEmployees] = useState<EmployeeOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showTargetForm, setShowTargetForm] = useState(false);
  const [targetForm, setTargetForm] = useState({ employeeId: '', periodMonth: currentMonth(), targetTzs: '' });
  const [showCommissionForm, setShowCommissionForm] = useState(false);
  const [commissionForm, setCommissionForm] = useState({ employeeId: '', periodMonth: currentMonth(), amountTzs: '', basis: '' });
  const [showAchievedForm, setShowAchievedForm] = useState(false);
  const [achievedTarget, setAchievedTarget] = useState<Target | null>(null);
  const [achievedValue, setAchievedValue] = useState('');
  const [saving, setSaving] = useState(false);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [d, e] = await Promise.all([
        adminApiFetch('/admin/sales-targets', accessToken, appSecretProof),
        adminApiFetch('/admin/employees', accessToken, appSecretProof),
      ]);
      setTargets(d.targets || []); setCommissions(d.commissions || []); setLeaderboard(d.leaderboard || []);
      setEmployees((e.employees || []).map((x: { id: number; name: string }) => ({ id: x.id, name: x.name })));
    } catch { setError('You do not have permission to view this page.'); }
    finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function submitTarget(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !targetForm.employeeId) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/sales-targets', accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ ...targetForm, employeeId: Number(targetForm.employeeId), targetTzs: Number(targetForm.targetTzs) }),
      });
      show('success', 'Target set.');
      setTargetForm({ employeeId: '', periodMonth: currentMonth(), targetTzs: '' });
      setShowTargetForm(false);
      load();
    } catch { show('error', 'Could not set that target.'); }
    finally { setSaving(false); }
  }

  async function submitCommission(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !commissionForm.employeeId) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/sales-targets/commissions', accessToken, appSecretProof, {
        method: 'POST', body: JSON.stringify({ ...commissionForm, employeeId: Number(commissionForm.employeeId), amountTzs: Number(commissionForm.amountTzs), basis: commissionForm.basis || undefined }),
      });
      show('success', 'Commission recorded.');
      setCommissionForm({ employeeId: '', periodMonth: currentMonth(), amountTzs: '', basis: '' });
      setShowCommissionForm(false);
      load();
    } catch { show('error', 'Could not record that commission.'); }
    finally { setSaving(false); }
  }

  function openAchievedForm(t: Target) {
    setAchievedTarget(t);
    setAchievedValue(t.achievedTzs);
    setShowAchievedForm(true);
  }

  async function submitAchieved(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !achievedTarget) return;
    setSaving(true);
    try {
      await adminApiFetch(`/admin/sales-targets/${achievedTarget.id}/achieved`, accessToken, appSecretProof, {
        method: 'PATCH', body: JSON.stringify({ achievedTzs: Number(achievedValue) }),
      });
      show('success', 'Progress updated.');
      setShowAchievedForm(false);
      load();
    } catch { show('error', 'Could not update progress.'); }
    finally { setSaving(false); }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;
  if (loading) return <StatCardSkeleton count={3} />;

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-xl font-bold">Sales Targets &amp; Commissions</h1>
        <div className="flex gap-2">
          <button onClick={() => setShowTargetForm(true)} className="border px-3 py-1.5 rounded-full text-xs transition-colors hover:bg-brand-bg">+ Set Target</button>
          <button onClick={() => setShowCommissionForm(true)} className="bg-brand-red text-white px-3 py-1.5 rounded-full text-xs transition-transform hover:scale-[1.03]">+ Add Commission</button>
        </div>
      </div>

      <div className="grid grid-cols-3 gap-4">
        <div className="bg-white p-4 rounded-xl border border-brand-border transition-all hover:shadow-md">
          <p className="text-xs text-gray-500">Targets This Period</p>
          {targets.slice(0, 4).map((t) => {
            const pct = Math.min(100, Math.round((Number(t.achievedTzs) / Number(t.targetTzs)) * 100) || 0);
            return (
              <div key={t.id} className="mt-2 cursor-pointer" onClick={() => openAchievedForm(t)} title="Click to update progress">
                <p className="text-xs">{t.employee.name}: TZS {Number(t.achievedTzs).toLocaleString()} / {Number(t.targetTzs).toLocaleString()} ({pct}%)</p>
                <div className="w-full bg-gray-100 h-2 rounded-full mt-1"><div className="bg-brand-red h-2 rounded-full transition-all duration-500" style={{ width: `${pct}%` }} /></div>
              </div>
            );
          })}
          {targets.length === 0 && <p className="text-xs text-gray-400 mt-2">No targets set yet.</p>}
        </div>

        <div className="bg-white p-4 rounded-xl border border-brand-border transition-all hover:shadow-md">
          <p className="text-xs text-gray-500">Commissions This Period</p>
          {commissions.slice(0, 5).map((c) => (
            <p key={c.id} className="text-xs mt-1">{c.employee.name}: TZS {Number(c.amountTzs).toLocaleString()} {c.basis && `(${c.basis})`}</p>
          ))}
          {commissions.length === 0 && <p className="text-xs text-gray-400 mt-2">No commissions recorded yet.</p>}
        </div>

        <div className="bg-white p-4 rounded-xl border border-brand-border transition-all hover:shadow-md">
          <p className="text-xs text-gray-500">Leaderboard</p>
          {leaderboard.map((l, i) => (
            <p key={l.employee} className="text-xs mt-1">{i + 1}. {l.employee} — TZS {l.achievedTzs.toLocaleString()}</p>
          ))}
          {leaderboard.length === 0 && <p className="text-xs text-gray-400 mt-2">No data yet.</p>}
        </div>
      </div>

      {showTargetForm && (
        <Modal title="Set Sales Target" onClose={() => setShowTargetForm(false)}>
          <form onSubmit={submitTarget} className="space-y-3">
            <select required value={targetForm.employeeId} onChange={(e) => setTargetForm({ ...targetForm, employeeId: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm">
              <option value="">Select employee…</option>
              {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
            </select>
            <input required type="month" value={targetForm.periodMonth} onChange={(e) => setTargetForm({ ...targetForm, periodMonth: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <input required type="number" placeholder="Target amount (TZS)" value={targetForm.targetTzs} onChange={(e) => setTargetForm({ ...targetForm, targetTzs: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Set Target'}</button>
          </form>
        </Modal>
      )}

      {showCommissionForm && (
        <Modal title="Add Commission" onClose={() => setShowCommissionForm(false)}>
          <form onSubmit={submitCommission} className="space-y-3">
            <select required value={commissionForm.employeeId} onChange={(e) => setCommissionForm({ ...commissionForm, employeeId: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm">
              <option value="">Select employee…</option>
              {employees.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
            </select>
            <input required type="month" value={commissionForm.periodMonth} onChange={(e) => setCommissionForm({ ...commissionForm, periodMonth: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <input required type="number" placeholder="Commission amount (TZS)" value={commissionForm.amountTzs} onChange={(e) => setCommissionForm({ ...commissionForm, amountTzs: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <input placeholder="Basis (e.g. 5% Supply, optional)" value={commissionForm.basis} onChange={(e) => setCommissionForm({ ...commissionForm, basis: e.target.value })}
              className="w-full border border-brand-border rounded-lg px-3 py-2 text-sm" />
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Add Commission'}</button>
          </form>
        </Modal>
      )}
      {showAchievedForm && achievedTarget && (
        <Modal title={`Update progress — ${achievedTarget.employee.name}`} onClose={() => setShowAchievedForm(false)}>
          <form onSubmit={submitAchieved} className="space-y-3">
            <div>
              <label className="text-xs font-medium text-gray-600">Achieved amount (TZS)</label>
              <input required type="number" min={0} autoFocus value={achievedValue} onChange={(e) => setAchievedValue(e.target.value)}
                className="mt-1 w-full border border-brand-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-red" />
            </div>
            <button disabled={saving} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {saving ? 'Saving…' : 'Update Progress'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
