import { format } from 'date-fns';
import { ExternalLink } from 'lucide-react';
import { Panel } from '@/components/ui/panel';
import { WeeklySnapshotCard } from '@/components/analysis/weekly-snapshot-card';
import type { RecentDevelopments } from '@/lib/types';

type RecentDevelopmentsSectionProps = {
  recentDevelopments: RecentDevelopments;
};

function formatDate(value: string) {
  const parsed = new Date(value);
  return Number.isNaN(parsed.getTime()) ? value : format(parsed, 'MMM dd, yyyy');
}

export function RecentDevelopmentsSection(props: RecentDevelopmentsSectionProps) {
  return (
    <section className="grid gap-6 xl:grid-cols-[minmax(280px,0.72fr)_minmax(0,1.28fr)]">
      <WeeklySnapshotCard snapshot={props.recentDevelopments.weeklySnapshot} />

      <Panel title="Recent Developments" subtitle="SEC-first event cards sourced from filings and attached analysis." className="pt-2">
        {props.recentDevelopments.items.length === 0 ? (
          <p className="text-sm text-[color:var(--terminal-muted)]">No recent development items are available for this ticker yet.</p>
        ) : (
          <div className="grid gap-3 md:grid-cols-2">
            {props.recentDevelopments.items.map((item) => (
              <article key={item.id} className="border-t border-[color:var(--line-weak)] pt-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <p className="text-xs uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
                      {item.kind} · {formatDate(item.publishedAt)}
                    </p>
                    <h3 className="mt-2 text-base font-semibold text-[color:var(--terminal-bright)]">{item.title}</h3>
                  </div>
                  <span className="text-[10px] uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
                    {item.source}
                  </span>
                </div>
                <p className="mt-3 text-sm leading-6 text-[color:var(--terminal-bright)]">{item.summary ?? 'No summary is available for this development item yet.'}</p>
                <div className="mt-4 flex items-center justify-between gap-3">
                  <p className="text-xs uppercase tracking-[0.14em] text-[color:var(--terminal-muted)]">
                    {item.accessionNumber ?? 'No accession'}
                  </p>
                  {item.url ? (
                    <a href={item.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs uppercase tracking-[0.14em] text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
                      Open filing
                      <ExternalLink className="size-3.5" />
                    </a>
                  ) : null}
                </div>
              </article>
            ))}
          </div>
        )}
      </Panel>
    </section>
  );
}
