'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import { Checkbox, FormControlLabel, Paper, Skeleton, Stack, TextField, Typography } from '@mui/material';
import { AppButton, AppIcon, 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';

/**
 * 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 [note, setNote] = useState('');
  const [checked, setChecked] = useState<Record<string, boolean>>({});

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

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

  const submit = () => {
    if (!note.trim()) {
      enqueueSnackbar(t('note_required'), { variant: 'error' });
      return;
    }
    const taskResults: TaskResult[] = tasks.map((task) => ({ label: task.label, done: Boolean(checked[task.id]) }));
    createNote.mutate(
      { bookingId, body: note.trim(), taskResults },
      {
        onSuccess: () => {
          enqueueSnackbar(t('note_saved'), { variant: 'success' });
          setNote('');
          setChecked({});
        },
        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: 2, border: '1px solid', borderColor: 'divider', borderTop: '3px solid var(--bal-secondary)' }}
        >
          <Stack 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} />
                ) : (
                  tasks.map((task) => (
                    <FormControlLabel
                      key={task.id}
                      control={
                        <Checkbox
                          checked={Boolean(checked[task.id])}
                          onChange={(e) => setChecked((c) => ({ ...c, [task.id]: e.target.checked }))}
                        />
                      }
                      label={task.label}
                    />
                  ))
                )}
              </Stack>
            ) : null}

            <TextField
              label={t('note_label')}
              placeholder={t('note_placeholder')}
              value={note}
              onChange={(e) => setNote(e.target.value.slice(0, VISIT_NOTE_MAX_LENGTH))}
              multiline
              minRows={3}
              fullWidth
            />

            <AppButton
              variant="contained"
              color="secondary"
              startIcon="notes"
              onClick={submit}
              disabled={createNote.isPending || !note.trim()}
              sx={{ alignSelf: 'flex-end' }}
            >
              {createNote.isPending ? tc('saving') : t('note_submit')}
            </AppButton>
          </Stack>
        </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>
  );
}
