/**
 * VendorDashboard - vendor dashboard (C2.1 restyle).
 *
 * Sections (stacked):
 *   1. 4 KPI tiles w/ deltas (active deals, today's orders, conversion, rating)
 *   2. VendorActivityFeed reading listVendorFeedEvents
 *   3. Top-3 active deals preview w/ VendorDealCard
 *   4. AI recs module (dismiss → POST /api/vendor/recommendations/:id/dismiss)
 *
 * Shell: VendorShell variant="dots" (sidebar + topbar on desktop, bottom-nav on mobile).
 */

'use client';

import { useState, type ReactNode } from 'react';
import { QueryBoundary } from '@platform-modules/ui-primitives';
import { VendorShell } from '@/components/ui/layout/VendorShell';
import { VendorKpiTile } from '@/components/ui/domain/vendor/VendorKpiTile';
import { VendorActivityFeed } from '@/components/ui/domain/vendor/VendorActivityFeed';
import { VendorDealCard } from '@/components/ui/domain/vendor/VendorDealCard';
import { AiRecommendationCard } from '@/components/ui/domain/vendor/AiRecommendationCard';
import { Button } from '@/components/ui/primitives/Button';
import { VendorDashboardSkeleton } from '@/components/ui/feedback/Skeleton/VendorDashboardSkeleton';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import type { Locale } from '@/lib/i18n';
import { useLocale, useT } from '@/lib/i18n/react';
import { interpolate } from '@/lib/i18n/interpolate';
import { formatCurrency, formatDealWindowEnd, formatFeedTimestamp } from '@/lib/format';
import { formatAgorotSigned } from '@/lib/money';
import { getCsrfToken } from '@/lib/csrf';
import { useVendorDashboardData } from './useVendorDashboardData';
import type {
  VendorAiRec,
  VendorFeedEvent,
  VendorActiveDeal,
  VendorNotification,
} from './useVendorDashboardData';
import type { ActivityFeedItemProps } from '@/components/ui/domain/vendor/VendorActivityFeed';
import { captureCaught } from '@/lib/observability';
import { SectionHeader } from '@/components/ui/layout/SectionHeader';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import { VendorStripeStatusBanner } from './VendorStripeStatusBanner';
import { RejectionBannerList } from '@/components/ui/domain/RejectionBannerList';
import { DraftsBanner } from '@/components/ui/domain/DraftsBanner';
import {
  Tooltip,
  TooltipTrigger,
  TooltipContent,
  TooltipProvider,
} from '@/components/ui/overlays/Tooltip';
import { MetricTile } from '@/components/ui/domain/MetricTile';
import { SegmentedControl } from '@/components/ui/primitives/SegmentedControl';
import { useDashboardDensity } from '@/features/dashboards/useDashboardDensity';

// ─── Helpers ─────────────────────────────────────────────────────────────────

function formatDelta(val: number | null | undefined, currency = false): string {
  const n = val ?? 0;
  if (currency) {
    const formatted = formatAgorotSigned(Math.round(n * 100));
    return n > 0 ? `+${formatted}` : formatted;
  }
  const sign = n >= 0 ? '+' : '';
  return `${sign}${String(n)}`;
}

function deltaVariant(val: number | null): 'up' | 'down' | 'neutral' {
  if (val == null) return 'neutral';
  if (val > 0) return 'up';
  if (val < 0) return 'down';
  return 'neutral';
}

function feedDealName(payload: Record<string, unknown>): string {
  const raw = payload.dealTitle ?? payload.title ?? payload.dealName;
  return typeof raw === 'string' ? raw.trim() : '';
}

const REC_KIND_LABEL_KEYS: Record<string, string> = {
  stock_nudge: 'rec_kind_stock_nudge',
  pricing_suggestion: 'rec_kind_pricing_suggestion',
  schedule_opportunity: 'rec_kind_schedule_opportunity',
};

// ─── Feed event → ActivityFeed item mapping ───────────────────────────────────

const FEED_WARN_EVENTS = new Set([
  'vendor.deal.critical_window',
  'vendor.purchase.refunded',
  'vendor.account.frozen',
  'vendor.account.rejected',
]);

function feedEventToItem(
  e: VendorFeedEvent,
  t: (key: string) => string,
  tFeed: (key: string) => string,
  locale: Locale,
): ActivityFeedItemProps & { id: string } {
  const labelMap: Record<string, string> = {
    'vendor.deal.tier_passed': t('event_tier_passed'),
    'vendor.deal.critical_window': t('event_critical_window'),
    'vendor.purchase.redeemed': t('event_redeemed'),
    'vendor.purchase.refunded': t('event_refunded'),
    'vendor.review.received': t('event_review_received'),
    'vendor.account.approved': t('event_account_approved'),
    'vendor.account.frozen': t('event_account_frozen'),
    'vendor.account.unfrozen': t('event_account_unfrozen'),
    'vendor.account.rejected': t('event_account_rejected'),
  };

  const deal = feedDealName(e.payload);
  let title = labelMap[e.eventType] ?? t('event_unknown');
  if (e.eventType === 'vendor.deal.tier_passed' || e.eventType === 'vendor.deal.critical_window') {
    if (deal) {
      title = interpolate(title, { deal });
    } else {
      title =
        e.eventType === 'vendor.deal.tier_passed'
          ? tFeed('event_tier_passed_no_deal')
          : tFeed('event_critical_window_no_deal');
    }
  }

  return {
    id: e.id,
    title,
    tone: FEED_WARN_EVENTS.has(e.eventType) ? 'warn' : 'info',
    time: formatFeedTimestamp(e.createdAt, locale),
  };
}

function recBody(rec: VendorAiRec, t: (key: string) => string): string | null {
  const body = rec.payload?.body;
  if (typeof body === 'string' && body.trim()) return body.trim();
  const kindKey = REC_KIND_LABEL_KEYS[rec.kind];
  return kindKey ? t(kindKey) : null;
}

// ─── Component ────────────────────────────────────────────────────────────────

export function VendorDashboard() {
  const t = useT('vendor_dashboard');
  const tNav = useT('nav');
  const dashboardQuery = useVendorDashboardData();
  const { density, setDensity } = useDashboardDensity('dashboard-density:vendor-dashboard');

  return (
    <VendorShell variant="dashboard" currentPath="/vendor/dashboard">
      <QueryBoundary
        query={dashboardQuery}
        skeleton={<VendorDashboardSkeleton />}
        errorFallback={() => (
          <EmptyState
            title={t('error_title')}
            description={t('error_desc')}
            action={
              <Button variant="primary" size="sm" onClick={() => void dashboardQuery.refetch()}>
                {t('retry')}
              </Button>
            }
          />
        )}
      >
        {(data) => (
          <div
            className="flex flex-col gap-6 p-4 lg:p-6"
            data-testid="instant-content:vendor-dashboard"
          >
            <section className="space-y-3">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <h2 className="text-text-primary text-2xl font-bold">{t('page_title')}</h2>
                  <p className="text-text-muted mt-1 text-sm">{t('hero_period_current_month')}</p>
                </div>
                <SegmentedControl
                  aria-label={t('density_label')}
                  size="sm"
                  value={density}
                  onChange={(value) => setDensity(value as 'comfortable' | 'dense')}
                  options={[
                    { value: 'comfortable', label: t('density_comfortable') },
                    { value: 'dense', label: t('density_dense') },
                  ]}
                />
              </div>
              <MetricTile
                className="w-full"
                label={t('hero_metric_label')}
                value={formatCurrency(data.metrics.earnedThisMonth)}
                countUpValue={data.metrics.earnedThisMonth}
                formatCountUpValue={(value) => formatCurrency(value)}
                periodLabel={t('hero_period_current_month')}
                tone="success"
              />
            </section>
            {data.vendor && (
              <>
                <VendorStripeStatusBanner
                  stripeAccountId={data.vendor.stripeAccountId}
                  stripeOnboardingState={data.vendor.stripeOnboardingState}
                />
                {data.vendor.imageRejections.length > 0 && (
                  <RejectionBannerList notifications={data.vendor.imageRejections} />
                )}
                {data.vendor.draftsCount > 0 && <DraftsBanner count={data.vendor.draftsCount} />}
              </>
            )}
            {data.dailyInsight && <DailyInsightSection insight={data.dailyInsight} />}
            <KpiSection metrics={data.metrics} />
            <NotificationsSection notifications={data.notifications} />
            <FeedSection feedEvents={data.feedEvents} dense={density === 'dense'} />
            <TopDealsSection deals={data.topActiveDeals} dense={density === 'dense'} />
            <AiRecsSection aiRecs={data.aiRecs} />
            <section aria-label={tNav('support_center')} className="pt-2">
              <Button variant="ghost" size="sm" asChild>
                <a href="/support/tickets/new?agentDef=vendor-support">{tNav('support_center')}</a>
              </Button>
            </section>
          </div>
        )}
      </QueryBoundary>
    </VendorShell>
  );
}

// ─── KPI Section ─────────────────────────────────────────────────────────────

interface KpiSectionProps {
  metrics: NonNullable<ReturnType<typeof useVendorDashboardData>['data']>['metrics'];
}

function KpiTileWithTooltip({ tooltip, children }: { tooltip?: string; children: ReactNode }) {
  if (!tooltip) return <>{children}</>;
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <div className="h-full">{children}</div>
      </TooltipTrigger>
      <TooltipContent>{tooltip}</TooltipContent>
    </Tooltip>
  );
}

function KpiSection({ metrics }: KpiSectionProps) {
  const t = useT('vendor_dashboard');
  const { deltas } = metrics;
  const deltaTooltip = t('kpi_delta_tooltip');

  return (
    <TooltipProvider>
      <section aria-labelledby="kpi-heading">
        <h2 id="kpi-heading" className="text-text-primary mb-3 text-sm font-semibold">
          {t('kpi_title')}
        </h2>
        <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
          <VendorKpiTile
            label={t('kpi_active_deals')}
            value={String(metrics.activeDealsCount)}
            data-testid="kpi-active-deals"
          />
          <KpiTileWithTooltip tooltip={t('kpi_earned_tooltip')}>
            <VendorKpiTile
              label={t('earnedThisMonth')}
              value={formatCurrency(metrics.earnedThisMonth)}
              delta={deltas ? formatDelta(deltas.revenueDelta, true) : undefined}
              deltaVariant={deltas ? deltaVariant(deltas.revenueDelta) : 'neutral'}
              deltaTooltip={deltas ? deltaTooltip : undefined}
              data-testid="kpi-earned"
            />
          </KpiTileWithTooltip>
          <VendorKpiTile
            label={t('kpi_customers')}
            value={String(metrics.customersThisMonth ?? 0)}
            data-testid="kpi-customers"
          />
          <KpiTileWithTooltip tooltip={t('kpi_repeat_customers_tooltip')}>
            <VendorKpiTile
              label={t('kpi_repeat_customers')}
              value={String(metrics.returnedToBuy ?? 0)}
              data-testid="kpi-returned-to-buy"
            />
          </KpiTileWithTooltip>
        </div>
      </section>
    </TooltipProvider>
  );
}

// ─── Feed Section ─────────────────────────────────────────────────────────────

interface FeedSectionProps {
  feedEvents: VendorFeedEvent[];
  dense?: boolean;
}

function FeedSection({ feedEvents, dense = false }: FeedSectionProps) {
  const t = useT('vendor_dashboard');
  const tFeed = useT('vendor_activity_feed');
  const { locale } = useLocale();
  const items = feedEvents.map((e) =>
    feedEventToItem(e, t as (key: string) => string, tFeed as (key: string) => string, locale),
  );

  return (
    <section aria-labelledby="feed-heading">
      <h2 id="feed-heading" className="text-text-primary mb-3 text-sm font-semibold">
        {t('feed_title')}
      </h2>
      {items.length === 0 ? (
        <EmptyState
          title={t('feed_empty_title')}
          description={t('feed_empty')}
          action={
            <Button variant="secondary" size="sm" asChild>
              <a href="/vendor/deals/new">{t('add_first_deal')}</a>
            </Button>
          }
        />
      ) : (
        <div className={dense ? 'text-sm' : undefined}>
          <VendorActivityFeed items={items} />
        </div>
      )}
    </section>
  );
}

// ─── Daily Insight Section ────────────────────────────────────────────────────

interface DailyInsightSectionProps {
  insight: string;
}

function DailyInsightSection({ insight }: DailyInsightSectionProps) {
  const t = useT('vendor_dashboard');
  return (
    <section aria-labelledby="daily-insight-heading" data-testid="daily-insight">
      <h2 id="daily-insight-heading" className="text-text-primary mb-2 text-sm font-semibold">
        {t('daily_insight_title')}
      </h2>
      <InlineNotice tone="info" description={insight} />
    </section>
  );
}

// ─── Notifications Section ────────────────────────────────────────────────────

interface NotificationsSectionProps {
  notifications: VendorNotification[];
}

function NotificationsSection({ notifications }: NotificationsSectionProps) {
  const t = useT('vendor_dashboard');

  if (notifications.length === 0) return null;

  return (
    <section aria-labelledby="notifications-heading" data-testid="notification-list">
      <h2 id="notifications-heading" className="text-text-primary mb-3 text-sm font-semibold">
        {t('notifications_title')}
      </h2>
      <ul className="flex flex-col gap-2">
        {notifications.map((n) => (
          <li key={n.id} data-testid="notification-item">
            <InlineNotice
              tone={
                n.tone === 'danger'
                  ? 'danger'
                  : n.tone === 'warning'
                    ? 'warning'
                    : n.tone === 'success'
                      ? 'success'
                      : 'info'
              }
              title={n.title}
              description={n.sub}
            />
          </li>
        ))}
      </ul>
    </section>
  );
}

// ─── Top Deals Section ────────────────────────────────────────────────────────

interface TopDealsSectionProps {
  deals: VendorActiveDeal[];
  dense?: boolean;
}

function TopDealsSection({ deals, dense = false }: TopDealsSectionProps) {
  const t = useT('vendor_dashboard');
  const tCard = useT('vendor_deal_card');
  const { locale } = useLocale();

  return (
    <section aria-labelledby="top-deals-heading">
      <SectionHeader
        title={t('top_deals_title')}
        actionHref="/vendor/deals"
        actionLabel={t('top_deals_view_all')}
      />
      {deals.length === 0 ? (
        <EmptyState
          title={t('top_deals_empty_title')}
          description={t('no_active_deals_desc')}
          action={
            <Button variant="secondary" size="sm" asChild>
              <a href="/vendor/deals/new">{t('add_first_deal')}</a>
            </Button>
          }
        />
      ) : (
        <ul className={dense ? 'flex flex-col gap-2' : 'flex flex-col gap-3'}>
          {deals.map((deal) => {
            const sold = deal.stockTotal - deal.stockRemaining;
            const isGroupDeal = deal.dealType === 'GROUP';
            return (
              <li key={deal.id} data-testid="top-deal-card">
                <VendorDealCard
                  variant="active"
                  title={deal.title}
                  href={`/vendor/deals/${deal.id}`}
                  dealType={deal.dealType}
                  participants={sold}
                  targetParticipants={deal.stockTotal}
                  progressDetailText={
                    deal.dealType && !isGroupDeal
                      ? interpolate(t('top_deals_stock_label'), { sold, total: deal.stockTotal })
                      : undefined
                  }
                  timeRemaining={
                    deal.windowEnd
                      ? formatDealWindowEnd(deal.windowEnd, locale, {
                          endsAtTime: tCard('ends_at_time'),
                          endsOnDateTime: tCard('ends_on_datetime'),
                          endsInDays: tCard('ends_in_days'),
                        })
                      : undefined
                  }
                  imageSrc={deal.imageSrc || undefined}
                  imageAlt={deal.imageAlt || deal.title}
                />
              </li>
            );
          })}
        </ul>
      )}
    </section>
  );
}

// ─── AI Recs Section ──────────────────────────────────────────────────────────

interface AiRecsSectionProps {
  aiRecs: VendorAiRec[];
}

function AiRecsSection({ aiRecs }: AiRecsSectionProps) {
  const t = useT('vendor_dashboard');
  const [dismissed, setDismissed] = useState<Set<string>>(new Set());

  const visible = aiRecs
    .filter((r) => !dismissed.has(r.id))
    .map((r) => ({ rec: r, body: recBody(r, t as (key: string) => string) }))
    .filter((item): item is { rec: VendorAiRec; body: string } => item.body != null);

  if (visible.length === 0) return null;

  async function handleDismiss(id: string) {
    setDismissed((prev) => new Set([...prev, id]));
    try {
      const csrf = getCsrfToken();
      await fetch(`/api/vendor/recommendations/${id}/dismiss`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-csrf-token': csrf },
      });
    } catch (err) {
      captureCaught(err, {
        scope: 'features.vendor-dashboard.VendorDashboard',
        severity: 'warning',
      });
    }
  }

  return (
    <section aria-labelledby="ai-recs-heading">
      <h2 id="ai-recs-heading" className="text-text-primary mb-3 text-sm font-semibold">
        {t('ai_recs_title')}
      </h2>
      <ul className="flex flex-col gap-3">
        {visible.map(({ rec, body }) => (
          <li key={rec.id}>
            <AiRecommendationCard
              body={body}
              detail={rec.payload?.detail ? String(rec.payload.detail) : undefined}
              onDismiss={() => void handleDismiss(rec.id)}
            />
          </li>
        ))}
      </ul>
    </section>
  );
}
