'use client';
import { FunctionComponent, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import {
  Box,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Skeleton,
  Stack,
  Typography,
} from '@mui/material';
import { AppButton, EmptyState, ErrorState, VariantCard } from '@/components';
import { useMyVariants, useSetVariantActive } from '@/services/catalog';
import type { NurseServiceVariant } from '@/services/catalog/types';
import PublishGate from './PublishGate';

interface MyServicesListProps {
  onAdd: () => void;
  onEdit: (variant: NurseServiceVariant) => void;
}

/**
 * The nurse's offerings list (`ListMyVariants`) — active + inactive variants as `VariantCard`s, with
 * loading skeletons and a prominent empty state. Deactivate opens a confirm dialog (soft only — the
 * variant becomes unbookable and drops out of search, never deleted); reactivating an inactive row is
 * non-destructive, so it fires directly. Mutations invalidate `myVariants` via the hook.
 */
const MyServicesList: FunctionComponent<MyServicesListProps> = ({ onAdd, onEdit }) => {
  const t = useTranslations('services');
  const tc = useTranslations('common');
  const { enqueueSnackbar } = useSnackbar();

  const { data, isLoading, isError, refetch } = useMyVariants();
  const setActive = useSetVariantActive();
  const [deactivateTarget, setDeactivateTarget] = useState<NurseServiceVariant | null>(null);

  const variants = data?.items ?? [];
  const isEmpty = !isLoading && !isError && variants.length === 0;

  const toggleActive = (variant: NurseServiceVariant) => {
    // Deactivating is guarded by a confirm; reactivating is safe, so it fires immediately.
    if (variant.isActive) {
      setDeactivateTarget(variant);
      return;
    }
    setActive.mutate(
      { id: variant.id, isActive: true },
      {
        onSuccess: () => enqueueSnackbar(t('activated_toast'), { variant: 'success' }),
        onError: () => enqueueSnackbar(t('toggle_error'), { variant: 'error' }),
      },
    );
  };

  const confirmDeactivate = () => {
    if (!deactivateTarget) return;
    const id = deactivateTarget.id;
    setDeactivateTarget(null);
    setActive.mutate(
      { id, isActive: false },
      {
        onSuccess: () => enqueueSnackbar(t('deactivated_toast'), { variant: 'success' }),
        onError: () => enqueueSnackbar(t('toggle_error'), { variant: 'error' }),
      },
    );
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: 640 }}>
      <Stack direction="row" sx={{ alignItems: 'flex-start', justifyContent: 'space-between', gap: 2 }}>
        <Box>
          <Typography variant="h5" component="h1">
            {t('title')}
          </Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('subtitle')}
          </Typography>
        </Box>
        {!isEmpty && !isLoading && !isError ? (
          <AppButton color="primary" variant="contained" startIcon="add" onClick={onAdd} sx={{ flexShrink: 0 }}>
            {t('add')}
          </AppButton>
        ) : null}
      </Stack>

      <PublishGate />

      {isLoading ? (
        <Stack sx={{ gap: 1.5 }}>
          {[0, 1].map((key) => (
            <Skeleton key={key} variant="rounded" height={150} sx={{ borderRadius: 2 }} />
          ))}
        </Stack>
      ) : isError ? (
        <ErrorState message={t('list_error')} retryLabel={tc('retry')} onRetry={() => refetch()} />
      ) : isEmpty ? (
        <EmptyState
          icon="services"
          title={t('empty_title')}
          body={t('empty_body')}
          action={
            <AppButton color="primary" variant="contained" startIcon="add" onClick={onAdd}>
              {t('add')}
            </AppButton>
          }
        />
      ) : (
        <Stack sx={{ gap: 1.5 }}>
          {variants.map((variant) => (
            <VariantCard
              key={variant.id}
              variant={variant}
              onEdit={() => onEdit(variant)}
              onToggleActive={() => toggleActive(variant)}
            />
          ))}
        </Stack>
      )}

      <Dialog open={Boolean(deactivateTarget)} onClose={() => setDeactivateTarget(null)}>
        <DialogTitle>{t('deactivate_title')}</DialogTitle>
        <DialogContent>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('deactivate_body')}
          </Typography>
        </DialogContent>
        <DialogActions>
          <AppButton variant="text" onClick={() => setDeactivateTarget(null)}>
            {tc('cancel')}
          </AppButton>
          <AppButton color="error" variant="contained" onClick={confirmDeactivate}>
            {t('deactivate_confirm')}
          </AppButton>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default MyServicesList;
