'use client';
import { ReactNode, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import { Box, Divider, Paper, Skeleton, Stack, TextField, Typography } from '@mui/material';
import { AppButton, StatusChip, TrustBadge } from '@/components';
import { AdminEmptyState, AdminErrorState, ConfirmDialog } from '@/components/admin';
import { useAdminCapabilities } from '@/hooks';
import { ROUTES } from '@/constants';
import {
  usePartnerCenter,
  useCenterSponsoredNurses,
  useVerifyPartnerCenter,
  useSetPartnerCenterActive,
  useAssignNurseToPartnerCenter,
} from '@/services/partnerCenter';
import { CENTER_STATE_KIND, PartnerCenterFormDialog } from '../page';

/**
 * Partner-center admin detail (f15) — the licensing/settlement record for one center, its lifecycle actions,
 * and its sponsored-nurse roster. Admins with `canManagePartners` may verify & activate a center (records
 * licensing approval), suspend/reactivate it, edit it, and add/remove sponsored nurses. The settlement IBAN
 * is only ever shown masked (last-4); it is never rendered in plaintext (write-then-masked). The server
 * enforces every command's scope — the capability flag only hides controls.
 */
export default function AdminPartnerCenterDetailPage() {
  const t = useTranslations('admin');
  const locale = useLocale();
  const router = useRouter();
  const caps = useAdminCapabilities();
  const { enqueueSnackbar } = useSnackbar();

  const params = useParams<{ id: string }>();
  const parsed = Number(params?.id);
  const centerId = Number.isFinite(parsed) && parsed > 0 ? parsed : 0;

  const center = usePartnerCenter(centerId || null);
  const roster = useCenterSponsoredNurses(centerId || null);
  const verify = useVerifyPartnerCenter(centerId);
  const setActive = useSetPartnerCenterActive(centerId);
  const assignNurse = useAssignNurseToPartnerCenter(centerId);

  const [confirmVerify, setConfirmVerify] = useState(false);
  const [editing, setEditing] = useState(false);
  const [assignId, setAssignId] = useState('');

  const data = center.data;

  const onVerifyConfirm = () => {
    verify.mutate(undefined, {
      onSuccess: () => {
        enqueueSnackbar(t('partner_verified_toast'), { variant: 'success' });
        setConfirmVerify(false);
      },
    });
  };

  const onAssign = () => {
    const nurseProfileId = Number(assignId);
    if (!Number.isFinite(nurseProfileId) || nurseProfileId <= 0) return;
    assignNurse.mutate(
      { nurseProfileId, unlink: false },
      {
        onSuccess: () => {
          enqueueSnackbar(t('partner_nurse_assigned'), { variant: 'success' });
          setAssignId('');
        },
      },
    );
  };

  const onRemove = (nurseProfileId: number) => {
    assignNurse.mutate(
      { nurseProfileId, unlink: true },
      { onSuccess: () => enqueueSnackbar(t('partner_nurse_assigned'), { variant: 'success' }) },
    );
  };

  const back = (
    <AppButton
      variant="text"
      color="primary"
      startIcon="partners"
      onClick={() => router.push(`/${locale}${ROUTES.ADMIN_PARTNERS}`)}
      sx={{ alignSelf: 'flex-start' }}
    >
      {t('back')}
    </AppButton>
  );

  if (center.isLoading) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {back}
        <Skeleton variant="rounded" height={80} />
        <Skeleton variant="rounded" height={220} />
        <Skeleton variant="rounded" height={160} />
      </Box>
    );
  }

  if (center.isError) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {back}
        <AdminErrorState message={t('error_generic')} retryLabel={t('retry')} onRetry={() => center.refetch()} />
      </Box>
    );
  }

  if (!data) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {back}
        <AdminEmptyState icon="partners" title={t('partner_empty')} />
      </Box>
    );
  }

  const commissionPercent = new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 2 }).format(
    data.commissionRate,
  );

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <Stack sx={{ gap: 0.75 }}>
        {back}
        <Stack direction="row" sx={{ gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}>
          <Typography variant="h5" component="h1" sx={{ fontWeight: 800 }}>
            {t('partner_detail_title')}
          </Typography>
          <StatusChip status={CENTER_STATE_KIND[data.onboardingState]} label={t(`center_state_${data.onboardingState}`)} />
        </Stack>
        <Typography variant="subtitle1" sx={{ color: 'text.secondary' }}>
          {data.name}
        </Typography>
      </Stack>

      <Paper elevation={0} sx={{ p: 2.5, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
        <Stack divider={<Divider flexItem />} sx={{ gap: 1.25 }}>
          <DetailRow label={t('partner_legal_type')}>{data.legalEntityType || '—'}</DetailRow>
          <DetailRow label={t('partner_permit')}>{data.mohEstablishmentPermitNo || '—'}</DetailRow>
          <DetailRow label={t('partner_tech_director')}>{data.technicalDirectorLicenseNo ?? '—'}</DetailRow>
          <DetailRow label={t('partner_enamad')}>{data.enamadCode ?? '—'}</DetailRow>
          <DetailRow label={t('partner_commission')}>{commissionPercent}</DetailRow>
          <DetailRow label={t('partner_is_mor')}>{t(data.isMerchantOfRecord ? 'yes' : 'no')}</DetailRow>
          <DetailRow label={t('partner_iban')}>
            <Box component="span" dir="ltr">
              {data.settlementIbanMasked ?? '—'}
            </Box>
          </DetailRow>
        </Stack>
      </Paper>

      {caps.canManagePartners ? (
        <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
          {data.verifiedAt == null ? (
            <AppButton
              variant="contained"
              color="primary"
              startIcon="verified"
              onClick={() => setConfirmVerify(true)}
              disabled={verify.isPending}
            >
              {t('partner_verify')}
            </AppButton>
          ) : null}
          <AppButton
            variant="outlined"
            color="primary"
            onClick={() => setActive.mutate(!data.isActive)}
            disabled={setActive.isPending}
          >
            {t(data.isActive ? 'partner_suspend' : 'partner_activate')}
          </AppButton>
          <AppButton variant="outlined" color="inherit" startIcon="edit" onClick={() => setEditing(true)}>
            {t('partner_edit')}
          </AppButton>
        </Stack>
      ) : null}

      <Stack sx={{ gap: 1.5 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
          {t('partner_roster_title')}
        </Typography>

        {roster.isLoading ? (
          <Skeleton variant="rounded" height={120} />
        ) : (
          <Paper elevation={0} sx={{ border: '1px solid', borderColor: 'divider', borderRadius: 2, overflow: 'hidden' }}>
            <Stack divider={<Divider />}>
              {(roster.data ?? []).map((nurse) => (
                <Stack
                  key={nurse.nurseProfileId}
                  direction="row"
                  sx={{ p: 1.75, gap: 1.5, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}
                >
                  <Stack direction="row" sx={{ gap: 1, alignItems: 'center', flexWrap: 'wrap' }}>
                    <Typography variant="body2" sx={{ fontWeight: 700 }}>
                      {nurse.name}
                    </Typography>
                    <TrustBadge state={nurse.isVerified ? 'verified' : 'unverified'} />
                  </Stack>
                  {caps.canManagePartners ? (
                    <AppButton
                      variant="text"
                      color="error"
                      startIcon="delete"
                      onClick={() => onRemove(nurse.nurseProfileId)}
                      disabled={assignNurse.isPending}
                    >
                      {t('partner_unlink_nurse')}
                    </AppButton>
                  ) : null}
                </Stack>
              ))}
            </Stack>
          </Paper>
        )}

        {caps.canManagePartners ? (
          <Stack direction="row" sx={{ gap: 1, alignItems: 'flex-start', flexWrap: 'wrap' }}>
            <TextField
              size="small"
              type="number"
              label={t('partner_assign_nurse_ph')}
              value={assignId}
              onChange={(e) => setAssignId(e.target.value)}
              slotProps={{ htmlInput: { min: 1, step: 1 } }}
              sx={{ minWidth: 200 }}
            />
            <AppButton
              variant="contained"
              color="primary"
              startIcon="assign"
              onClick={onAssign}
              disabled={assignNurse.isPending || Number(assignId) <= 0}
              sx={{ mt: 0.25 }}
            >
              {t('partner_assign_nurse')}
            </AppButton>
          </Stack>
        ) : null}
      </Stack>

      <ConfirmDialog
        open={confirmVerify}
        title={t('partner_verify')}
        body={t('partner_verify_confirm')}
        confirmLabel={t('confirm')}
        cancelLabel={t('cancel')}
        onConfirm={onVerifyConfirm}
        onClose={() => setConfirmVerify(false)}
        loading={verify.isPending}
      />

      {editing ? <PartnerCenterFormDialog center={data} onClose={() => setEditing(false)} /> : null}
    </Box>
  );
}

/** One label/value line in the license/settlement block. */
function DetailRow({ label, children }: { label: string; children: ReactNode }) {
  return (
    <Stack direction="row" sx={{ gap: 1.5, justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap' }}>
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {label}
      </Typography>
      <Typography variant="body2" component="div" sx={{ fontWeight: 500, textAlign: 'end' }}>
        {children}
      </Typography>
    </Stack>
  );
}
