import { submitRankingAppeal } from '@/app/actions';
import { SubmitButton } from '@/components/Actions';
import { api } from '@/lib/api';
import { date } from '@/lib/format';
import { Card, Empty, PageHeader } from '@/components/ui';
import { ChartIcon, HistoryIcon, InfoIcon } from '@/components/Icons';

type R = {
  version: string | null;
  note: string;
  rankings: { city: string; area: string; position: number; cohort: number; score: number; calculatedAt: string; components: { key: string; label: string; score: number; weight: number | null }[] }[];
  history: { city: string; area: string; position: number; cohort: number; score: number; at: string }[];
};

/** What to improve, per component — only things backed by evidence */
const HOW: Record<string, string> = {
  credentials: 'Add verified licences and education under Credentials.',
  experience: 'Make sure your admission year and years in practice are on file.',
  specialization: 'Practice-area focus comes from your licence and matters; ask our team to correct wrong areas.',
  reputation: 'Comes from verified client reviews over time.',
  recognition: 'Add independent awards (pay-to-play awards score zero).',
  trackRecord: 'Add publicly sourced court matters under Credentials.',
  clientExperience: 'Respond to enquiries quickly.',
  profileQuality: 'Complete your profile: biography, photo, contact details, languages.',
  freshness: 'Keep details current; we re-verify periodically.',
};

export default async function Rankings() {
  const d = await api<R>('/me/rankings');
  const appeals = await api<{ id: number; reason: string; status: string; decisionNote: string | null }[]>('/portal/ranking-appeals');
  return (
    <>
      <PageHeader title="Rankings" icon={<ChartIcon className="h-5 w-5" />} description={`How each of your current rankings is calculated${d.version ? ` (methodology ${d.version})` : ''}. ${d.note}`} />
      {d.rankings.length ? (
        <div className="space-y-6">
          {d.rankings.map((r) => (
            <Card
              key={`${r.city}-${r.area}`}
              title={
                <span>
                  <span className="rank-figure mr-2 text-xl">#{r.position}</span>
                  {r.area}, {r.city} <span className="font-normal text-muted">of {r.cohort}</span>
                </span>
              }
              icon={<ChartIcon className="h-4 w-4" />}
              actions={<span className="num text-sm font-semibold">{r.score.toFixed(1)} / 100</span>}
            >
              <div className="overflow-x-auto">
                <table className="tbl">
                  <thead>
                    <tr>
                      <th>Component</th>
                      <th className="w-20 text-right">Weight</th>
                      <th className="w-64">Your score</th>
                      <th>How to improve the evidence</th>
                    </tr>
                  </thead>
                  <tbody>
                    {r.components.map((c) => (
                      <tr key={c.key}>
                        <td className="font-medium">{c.label}</td>
                        <td className="num text-right text-xs text-muted">{c.weight != null ? `${Math.round(c.weight * 100)}%` : '—'}</td>
                        <td>
                          <div className="flex items-center gap-2">
                            <div className="h-2 flex-1 overflow-hidden rounded-full bg-sunken" role="img" aria-label={`${c.score.toFixed(0)} out of 100`}>
                              <div className={`h-full rounded-full ${c.score >= 70 ? 'bg-ledger' : c.score >= 40 ? 'bg-brass' : 'bg-danger'}`} style={{ width: `${Math.max(2, Math.min(100, c.score))}%` }} />
                            </div>
                            <span className="num w-9 text-right text-xs">{c.score.toFixed(0)}</span>
                          </div>
                        </td>
                        <td className="text-xs text-ink-2">{HOW[c.key] ?? ''}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">Calculated {date(r.calculatedAt, true)}.</p>
            </Card>
          ))}
        </div>
      ) : (
        <Card>
          <Empty icon={<InfoIcon className="h-6 w-6" />}>You’re not ranked yet. Rankings need an active, verified licence and a practice area in a ranked city.</Empty>
        </Card>
      )}

      {d.history.length > 0 && (
        <Card title="History" icon={<HistoryIcon className="h-4 w-4" />} className="mt-6">
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Ranking</th>
                  <th className="text-right">Position</th>
                  <th className="text-right">Score</th>
                </tr>
              </thead>
              <tbody>
                {d.history.map((h, i) => (
                  <tr key={i}>
                    <td className="whitespace-nowrap text-xs text-muted">{date(h.at)}</td>
                    <td>
                      {h.area}, {h.city}
                    </td>
                    <td className="num text-right">
                      #{h.position} <span className="text-xs text-muted">of {h.cohort}</span>
                    </td>
                    <td className="num text-right">{h.score.toFixed(1)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}
      <Card title="Request a ranking review" className="mt-6">
        <form action={submitRankingAppeal} className="space-y-3 p-4 text-sm">
          <p className="text-muted">Ask our verification team to review incorrect or missing source evidence. A request does not directly change scores.</p>
          <label className="block">Reason<select name="reason" required className="field mt-1">{['incorrect_license','missing_experience','incorrect_practice_area','review_source_issue','missing_recognition','incorrect_professional_record','incorrect_source_data'].map((r) => <option key={r} value={r}>{r.replaceAll('_', ' ')}</option>)}</select></label>
          <label className="block">Evidence and source references<textarea name="evidence" minLength={20} maxLength={5000} required className="field mt-1" /></label>
          <SubmitButton>Request review</SubmitButton>
        </form>
        {appeals.map((r) => <div key={r.id} className="border-t border-rule p-4 text-sm"><p>{r.reason.replaceAll('_', ' ')}: {r.status}</p>{r.decisionNote && <p className="mt-1 text-muted">{r.decisionNote}</p>}</div>)}
      </Card>
    </>
  );
}
