'use client';
import { FunctionComponent, ReactElement, useState } from 'react';
import { useTranslations } from 'next-intl';
import Chip, { ChipProps } from '@mui/material/Chip';
import Dialog from '@mui/material/Dialog';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import IconButton from '@mui/material/IconButton';
import Stack from '@mui/material/Stack';
import AppIcon from '../common/AppIcon';
import VerificationPanel from '../VerificationPanel';
import { useNurseTrustBadge } from '@/services/verification';
import type { BadgeState } from '@/services/verification/types';

interface BadgeStyle {
  bg: string;
  fg: string;
  icon: string;
  labelKey: string;
}

// Colors resolve from the semantic --bal-* tokens so the badge switches with the color scheme.
// verified = green trust mark; unverified = neutral (never alarming); expired = amber "needs renewal"
// (distinct from unverified — a required credential lapsed). Never a hard-coded hex.
const BADGE_STYLE: Record<BadgeState, BadgeStyle> = {
  verified: { bg: 'var(--bal-success)', fg: 'var(--bal-success-contrast)', icon: 'verified', labelKey: 'badge_verified' },
  unverified: { bg: 'var(--bal-divider)', fg: 'var(--bal-text-secondary)', icon: 'info', labelKey: 'badge_unverified' },
  expired: { bg: 'var(--bal-warning)', fg: 'var(--bal-warning-contrast)', icon: 'warning', labelKey: 'badge_expired' },
};

export interface TrustBadgeProps extends Omit<ChipProps, 'color' | 'icon' | 'label' | 'onClick'> {
  /** The trust state — verified / unverified / expired. */
  state: BadgeState;
  /**
   * Opt-in explainer: when provided, the badge becomes tappable and opens a bottom-sheet (mobile) /
   * dialog (desktop) narrating what Balinyaar verified — the same `VerificationPanel` fed by
   * `useNurseTrustBadge(nurseId)` (fetched lazily, only once the explainer is actually opened). The
   * default (non-interactive) badge everywhere else is unchanged and calls no query hook at all — the
   * `useNurseTrustBadge` call lives entirely inside `InteractiveTrustBadge`, mounted only in this mode,
   * so a caller that never passes `nurseId` needs no `QueryClientProvider` in its tests.
   */
  nurseId?: number;
}

type ChipVisualProps = Pick<ChipProps, 'size' | 'sx'> & { 'data-badge-state': BadgeState };

/**
 * The public trust signal (the "✓ تاییدشده" mark) rendered on a nurse's profile and — reused unchanged
 * in f6 — on search results and the public nurse profile. Fed by `GetVerifiedBadgeQuery`; the state is
 * derived by the caller (`ownBadgeState`/`publicBadgeState`). Honest by construction: `verified` only
 * renders when the aggregate is approved; `expired` is visually distinct from never-verified.
 * @component TrustBadge
 */
const TrustBadge: FunctionComponent<TrustBadgeProps> = ({ state, nurseId, size = 'small', sx, ...rest }) => {
  const t = useTranslations('verification');
  const style = BADGE_STYLE[state];
  const label = t(style.labelKey);
  const icon: ReactElement = <AppIcon icon={style.icon} size={16} color={style.fg} />;
  const chipSx = { backgroundColor: style.bg, color: style.fg, fontWeight: 700, ...sx };
  const chipProps: ChipVisualProps = { size, sx: chipSx, 'data-badge-state': state };

  if (nurseId == null) {
    return <Chip label={label} icon={icon} {...chipProps} {...rest} />;
  }

  return (
    <InteractiveTrustBadge nurseId={nurseId} label={label} icon={icon} chipProps={chipProps} rest={rest} />
  );
};

/** Owns the tap-to-open state, the lazily-enabled `useNurseTrustBadge` fetch, and the explainer dialog —
 * split out so `TrustBadge` itself never calls a query hook in the default (non-interactive) mode. */
const InteractiveTrustBadge: FunctionComponent<{
  nurseId: number;
  label: string;
  icon: ReactElement;
  chipProps: ChipVisualProps;
  rest: Omit<ChipProps, 'color' | 'icon' | 'label' | 'onClick' | 'size' | 'sx'>;
}> = ({ nurseId, label, icon, chipProps, rest }) => {
  const t = useTranslations('verification');
  const [open, setOpen] = useState(false);

  // Lazy: only fetches once the explainer is opened (undefined disables the query otherwise).
  const { data: badge, isLoading, isError } = useNurseTrustBadge(open ? nurseId : undefined);

  return (
    <>
      <Chip
        label={label}
        icon={icon}
        clickable
        onClick={() => setOpen(true)}
        aria-label={t('explainer_open_label')}
        {...chipProps}
        {...rest}
      />
      <Dialog
        open={open}
        onClose={() => setOpen(false)}
        fullWidth
        data-trust-explainer
        sx={{ '& .MuiDialog-container': { alignItems: { xs: 'flex-end', sm: 'center' } } }}
        slotProps={{
          paper: {
            sx: {
              width: { xs: '100%', sm: 480 },
              m: { xs: 0, sm: 'auto' },
              borderRadius: { xs: 'var(--bal-radius-lg) var(--bal-radius-lg) 0 0', sm: 'var(--bal-radius-lg)' },
            },
          },
        }}
      >
        <DialogTitle sx={{ p: 0 }}>
          <Stack direction="row" sx={{ alignItems: 'center', justifyContent: 'space-between', px: 3, pt: 2.5 }}>
            {t('explainer_title')}
            <IconButton onClick={() => setOpen(false)} aria-label={t('explainer_close')} size="small">
              <AppIcon icon="close" size={20} />
            </IconButton>
          </Stack>
        </DialogTitle>
        <DialogContent sx={{ pb: 3 }}>
          <VerificationPanel badge={badge} isLoading={isLoading} isError={isError} />
        </DialogContent>
      </Dialog>
    </>
  );
};

export default TrustBadge;
