'use client';
import { useLocale, useTranslations } from 'next-intl';
import { FormProvider, useForm, useWatch } from 'react-hook-form';
import { useSnackbar } from 'notistack';
import { Checkbox, FormControlLabel, Paper, Skeleton, Stack, Typography } from '@mui/material';
import { AppButton, AppIcon, RhfControlGroup, RhfTextField, VisitNoteCard } from '@/components';
import { formatShamsiDate } from '@/utils';
import { useBookingDetail } from '@/services/bookings';
import { isBookingConfirmedOrBeyond } from '@/services/bookings/types';
import { useRecordAccess, usePatientCareRecord, usePatientHistory, useCreateVisitNote } from '@/services/patientRecords';
import { VISIT_NOTE_MAX_LENGTH } from '@/services/patientRecords/constants';
import type { TaskResult } from '@/services/patientRecords/types';

interface VisitNoteFormValues {
  note: string;
  /** Task id → ticked. One field so a whole submitted checklist resets in a single `reset`. */
  checked: Record<string, boolean>;
}

/**
 * E3 (نمای پرستار) — the nurse visit-note authoring, mounted **below** the f8 EVV banner on the nurse booking
 * detail. **Append-only:** the nurse ticks today's task checklist and writes a free-text note, then submits
 * ONE appended note. It exposes **no** medication/routine/task editing and never wires `updateCareRecord` —
 * append-only is a hard boundary. The nurse can read prior history for continuity (patient-scoped, so it
 * persists across nurse changes). The composer hides when the nurse lacks append access.
 */
export default function NurseVisitNotesPanel({ bookingId }: { bookingId: number }) {
  const t = useTranslations('records');
  const tc = useTranslations('common');
  const locale = useLocale();
  const { enqueueSnackbar } = useSnackbar();

  const booking = useBookingDetail(bookingId, 'nurse');
  const status = booking.data?.status;
  const patientId = booking.data?.patientId ?? -1;
  const engaged = status ? isBookingConfirmedOrBeyond(status) : false;

  const access = useRecordAccess(patientId, { enabled: engaged && patientId > 0 });
  const canAppend = access.data?.canAppendNote ?? false;
  const canView = access.data?.canView ?? false;

  const record = usePatientCareRecord(patientId, { enabled: engaged && patientId > 0 && canAppend });
  const history = usePatientHistory(patientId, 1, { enabled: engaged && patientId > 0 && canView });
  const createNote = useCreateVisitNote(patientId);

  const form = useForm<VisitNoteFormValues>({ mode: 'onTouched', defaultValues: { note: '', checked: {} } });
  const { control, handleSubmit, reset } = form;
  const note = useWatch({ control, name: 'note' });

  if (!booking.data || !engaged) return null;

  const tasks = record.data?.tasks ?? [];

  const submit = (values: VisitNoteFormValues) => {
    const taskResults: TaskResult[] = tasks.map((task) => ({ label: task.label, done: Boolean(values.checked[task.id]) }));
    createNote.mutate(
      { bookingId, body: values.note.trim(), taskResults },
      {
        onSuccess: () => {
          enqueueSnackbar(t('note_saved'), { variant: 'success' });
          reset({ note: '', checked: {} });
        },
        onError: () => enqueueSnackbar(t('note_error'), { variant: 'error' }),
      },
    );
  };

  const historyItems = history.data?.items ?? [];

  return (
    <Stack sx={{ gap: 2, maxWidth: 640, mx: 'auto', width: '100%' }}>
      {canAppend ? (
        <Paper
          elevation={0}
          sx={{ p: 2.5, borderRadius: 'var(--bal-radius-md)', border: '1px solid', borderColor: 'divider', borderTop: '3px solid var(--bal-secondary)' }}
        >
          <FormProvider {...form}>
            <Stack component="form" noValidate onSubmit={handleSubmit(submit)} sx={{ gap: 2 }}>
              <Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
                <AppIcon icon="notes" size={20} color="var(--bal-secondary)" />
                <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
                  {t('notes_title')}
                </Typography>
              </Stack>

              {record.isLoading || tasks.length > 0 ? (
                <Stack sx={{ gap: 0.5 }}>
                  <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
                    {t('tasks_checklist_title')}
                  </Typography>
                  {record.isLoading ? (
                    <Skeleton variant="rounded" height={80} />
                  ) : (
                    <RhfControlGroup<VisitNoteFormValues> name="checked">
                      {({ field }) => {
                        const ticked = (field.value as Record<string, boolean>) ?? {};
                        return (
                          <Stack>
                            {tasks.map((task) => (
                              <FormControlLabel
                                key={task.id}
                                control={
                                  <Checkbox
                                    checked={Boolean(ticked[task.id])}
                                    onChange={(event) =>
                                      field.onChange({ ...ticked, [task.id]: event.target.checked })
                                    }
                                  />
                                }
                                label={task.label}
                              />
                            ))}
                          </Stack>
                        );
                      }}
                    </RhfControlGroup>
                  )}
                </Stack>
              ) : null}

              <RhfTextField<VisitNoteFormValues>
                name="note"
                label={t('note_label')}
                placeholder={t('note_placeholder')}
                transform={(raw) => raw.slice(0, VISIT_NOTE_MAX_LENGTH)}
                rules={{ validate: (value) => String(value ?? '').trim().length > 0 || t('note_required') }}
                multiline
                minRows={3}
                fullWidth
              />

              <AppButton
                type="submit"
                variant="contained"
                color="secondary"
                startIcon="notes"
                disabled={createNote.isPending || !note.trim()}
                sx={{ alignSelf: 'flex-end' }}
              >
                {createNote.isPending ? tc('saving') : t('note_submit')}
              </AppButton>
            </Stack>
          </FormProvider>
        </Paper>
      ) : null}

      {canView ? (
        <Stack sx={{ gap: 1.5 }}>
          <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
            {t('continuity_title')}
          </Typography>
          {history.isLoading ? (
            <Skeleton variant="rounded" height={96} />
          ) : historyItems.length === 0 ? (
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {t('history_empty')}
            </Typography>
          ) : (
            historyItems.map((visitNote) => (
              <VisitNoteCard
                key={visitNote.id}
                note={visitNote}
                dateLabel={formatShamsiDate(visitNote.recordedAt, locale)}
                authorFallback={t('author_fallback')}
              />
            ))
          )}
        </Stack>
      ) : null}
    </Stack>
  );
}
