import Link from "next/link";
import { apiFetch } from "@/lib/api";

interface Me { email: string; tier: string; telegramLinked: boolean; clientCount: number; entryCount: number; }
interface Entry { id: string; hours: number; description: string; date: string; client: { name: string; hourlyRate: number; currency: string }; }

async function load() {
  const [meRes, entriesRes] = await Promise.all([
    apiFetch("/v1/auth/me"),
    apiFetch("/v1/entries"),
  ]);
  const me: Me | null = meRes.ok ? await meRes.json() : null;
  const entries: Entry[] = entriesRes.ok ? await entriesRes.json() : [];
  return { me, entries };
}

export default async function DashboardOverview() {
  const { me, entries } = await load();
  const totalHours = entries.reduce((s, e) => s + e.hours, 0);
  const totalAmount = entries.reduce((s, e) => s + e.hours * e.client.hourlyRate, 0);

  const byClient = entries.reduce<Record<string, { hours: number; amount: number; currency: string }>>((acc, e) => {
    const key = e.client.name;
    acc[key] = acc[key] || { hours: 0, amount: 0, currency: e.client.currency };
    acc[key].hours += e.hours;
    acc[key].amount += e.hours * e.client.hourlyRate;
    return acc;
  }, {});

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold mb-1">This month</h1>
        <p className="text-white/50 text-sm">{new Date().toLocaleString("en-US", { month: "long", year: "numeric" })}</p>
      </div>

      <div className="grid md:grid-cols-3 gap-4">
        <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
          <div className="text-xs uppercase text-white/40 font-mono mb-2">Hours</div>
          <div className="text-3xl font-bold">{totalHours.toFixed(1)}</div>
        </div>
        <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
          <div className="text-xs uppercase text-white/40 font-mono mb-2">Billable</div>
          <div className="text-3xl font-bold">${totalAmount.toFixed(0)}</div>
        </div>
        <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
          <div className="text-xs uppercase text-white/40 font-mono mb-2">Entries</div>
          <div className="text-3xl font-bold">{entries.length}</div>
        </div>
      </div>

      {!me?.telegramLinked && (
        <div className="bg-accent-500/10 border border-accent-500/30 rounded-xl p-5 flex items-start gap-3">
          <div className="text-2xl">💬</div>
          <div className="flex-1">
            <h3 className="font-bold mb-1">Connect Telegram</h3>
            <p className="text-sm text-white/60 mb-3">Log entries in plain language: open <a href="https://t.me/timechat_tracker_bot" target="_blank" rel="noreferrer" className="text-accent-400 underline">@timechat_tracker_bot</a> → /start</p>
          </div>
        </div>
      )}

      <div>
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-bold text-lg">By client</h2>
          <Link href="/dashboard/clients" className="text-sm text-accent-400 hover:text-accent-300">Manage rates →</Link>
        </div>
        {Object.keys(byClient).length === 0 ? (
          <div className="bg-ink-800/30 border border-white/10 rounded-xl p-8 text-center text-white/50">
            <p>No entries yet this month.</p>
            <p className="text-xs mt-2">Use Telegram bot to log hours.</p>
          </div>
        ) : (
          <div className="space-y-2">
            {Object.entries(byClient).map(([name, data]) => (
              <div key={name} className="bg-ink-800/50 border border-white/10 rounded-lg p-4 flex items-center justify-between">
                <div>
                  <div className="font-semibold">{name}</div>
                  <div className="text-xs text-white/40">{data.hours.toFixed(1)}h</div>
                </div>
                <div className="text-right">
                  <div className="font-bold">{data.amount.toFixed(0)} {data.currency}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
