'use client';
import { useTranslations } from 'next-intl';
import { Alert, Box, Paper, Skeleton, Stack, Typography } from '@mui/material';
import { AdminEmptyState, AdminPageHeader } from '@/components/admin';
import { StatusChip } from '@/components';
import type { CenterOnboardingState, PartnerCenter } from '@/services/partnerCenter/types';
import { useMyPartnerCenter } from '@/services/partnerCenter';

/**
 * Partner portal home (f15) — the signed-in center admin's **own** center at a glance (a separate authz
 * scope from /admin; tenancy is server-enforced). `useMyPartnerCenter` doubles as the access gate: a
 * 403/404 (non-owner / no center) surfaces the non-leaking access-denied state, never any center data.
 * On success it shows the onboarding banner (draft/pending/suspended), the license block, the
 * merchant-of-record indicator, and the masked settlement IBAN. Read-only.
 */
export default function PartnerHomeScreen() {
  const t = useTranslations('partner');
  const center = useMyPartnerCenter();

  if (center.isLoading) {
    return (
      <Stack sx={{ gap: 3 }}>
        <Skeleton variant="rounded" height={72} />
        <Skeleton variant="rounded" height={64} />
        <Skeleton variant="rounded" height={220} />
      </Stack>
    );
  }

  // The center query is the portal's access gate — a 403/404 means the caller owns no center.
  if (center.isError || !center.data) {
    return <AdminEmptyState icon="lock" title={t('access_denied')} />;
  }

  const c = center.data;

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <AdminPageHeader
        title={t('home_title')}
        subtitle={t('home_subtitle')}
        actions={
          <StatusChip
            status={c.isMerchantOfRecord ? 'active' : 'neutral'}
            label={c.isMerchantOfRecord ? t('is_mor_yes') : t('is_mor_no')}
          />
        }
      />

      <OnboardingBanner state={c.onboardingState} />

      <LicenseBlock center={c} />
    </Box>
  );
}

/**
 * Onboarding/verification banner keyed off `onboardingState`. `verified` shows a subtle chip instead of a
 * banner; every other state shows an MUI `Alert` (draft/suspended → warning, pending → info).
 */
function OnboardingBanner({ state }: { state: CenterOnboardingState }) {
  const t = useTranslations('partner');
  const ta = useTranslations('admin');

  if (state === 'verified') {
    return (
      <Box>
        <StatusChip status="verified" label={ta('center_state_verified')} />
      </Box>
    );
  }

  const banner: Record<Exclude<CenterOnboardingState, 'verified'>, { severity: 'warning' | 'info'; key: string }> = {
    draft: { severity: 'warning', key: 'state_banner_draft' },
    pending_verification: { severity: 'info', key: 'state_banner_pending' },
    suspended: { severity: 'warning', key: 'state_banner_suspended' },
  };
  const { severity, key } = banner[state];

  return (
    <Alert severity={severity} sx={{ borderRadius: 2 }}>
      {t(key)}
    </Alert>
  );
}

/** License details + merchant-of-record settlement IBAN (masked last-4). Nulls render as an em dash. */
function LicenseBlock({ center }: { center: PartnerCenter }) {
  const t = useTranslations('partner');

  return (
    <Paper elevation={0} sx={{ p: 2.5, borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
      <Typography variant="subtitle1" sx={{ fontWeight: 800, mb: 2 }}>
        {t('license_title')}
      </Typography>
      <Stack sx={{ gap: 1.5 }}>
        <DetailRow label={t('permit')} value={center.mohEstablishmentPermitNo} />
        <DetailRow label={t('tech_director')} value={center.technicalDirectorLicenseNo} />
        <DetailRow label={t('enamad')} value={center.enamadCode} />
        <DetailRow label={t('legal_type')} value={center.legalEntityType} />
        {center.isMerchantOfRecord ? (
          <DetailRow label={t('settlement_iban')} value={center.settlementIbanMasked} ltr />
        ) : null}
      </Stack>
    </Paper>
  );
}

/** One label → value row. `ltr` forces LTR display for latin/numeric values (IBAN) inside an RTL page. */
function DetailRow({ label, value, ltr }: { label: string; value: string | null; ltr?: boolean }) {
  return (
    <Stack
      direction="row"
      sx={{ gap: 2, alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap' }}
    >
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {label}
      </Typography>
      {ltr ? (
        <Typography component="span" dir="ltr" variant="body2" sx={{ fontWeight: 500, fontFamily: 'monospace' }}>
          {value ?? '—'}
        </Typography>
      ) : (
        <Typography variant="body2" sx={{ fontWeight: 500 }}>
          {value ?? '—'}
        </Typography>
      )}
    </Stack>
  );
}
