import {
  mdiArrowLeft,
  mdiCalendarClock,
  mdiCheckCircleOutline,
  mdiContentSaveOutline,
  mdiFileDocumentOutline,
  mdiLinkVariant,
  mdiMicrophoneOutline,
  mdiPlus,
  mdiTarget,
  mdiTrashCanOutline,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React from 'react';
import type { ReactElement } from 'react';
import BaseIcon from '../../components/BaseIcon';
import SectionMain from '../../components/SectionMain';
import { getPageTitle } from '../../config';
import LayoutAuthenticated from '../../layouts/Authenticated';

type ActionItem = {
  id: string;
  sessionId?: string;
  title: string;
  status: string;
  due_at?: string;
  notes?: string;
};

type PrepBrief = {
  id: string;
  sessionId?: string;
  previous_summary?: string;
  open_commitments?: string;
  suggested_questions?: string;
  sensitive_topics?: string;
  client_reflection?: string;
};

type Resource = {
  id: string;
  title: string;
  description?: string;
  url?: string;
};

type Session = {
  id: string;
  title: string;
  ai_summary?: string;
  transcript_notes?: string;
  key_topics?: string;
  commitments?: string;
  homework?: string;
  follow_up_email?: string;
  next_session_prep?: string;
  private_coach_notes?: string;
  shared_client_notes?: string;
  audio_url?: string;
  audio_filename?: string;
  audio_mime_type?: string;
  audio_size?: number;
  session_at?: string;
  status?: string;
};

type Client = {
  id: string;
  name: string;
  email: string;
  status: string;
  goals?: string;
  notes?: string;
  company?: string;
  role_title?: string;
  tags?: string;
  next_session_at?: string;
  last_session_at?: string;
  ai_processing_consent_granted?: boolean;
  ai_processing_consent_at?: string;
  recording_consent_granted?: boolean;
  recording_consent_at?: string;
  consent_withdrawn_at?: string;
  reminders_enabled?: boolean;
  reminder_minutes?: number;
  sessions?: Session[];
  action_items?: ActionItem[];
  resources?: Resource[];
  prep_briefs?: PrepBrief[];
  package?: {
    title?: string;
  };
};

type ClientForm = {
  name: string;
  email: string;
  status: string;
  company: string;
  role_title: string;
  tags: string;
  goals: string;
  notes: string;
  next_session_at: string;
};

function formFromClient(client: Client): ClientForm {
  return {
    name: client.name || '',
    email: client.email || '',
    status: client.status || 'active',
    company: client.company || '',
    role_title: client.role_title || '',
    tags: client.tags || '',
    goals: client.goals || '',
    notes: client.notes || '',
    next_session_at: toDateTimeInput(client.next_session_at),
  };
}

function toDateTimeInput(value?: string) {
  if (!value) {
    return '';
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return '';
  }

  return date.toISOString().slice(0, 16);
}

function displayDateTime(value?: string) {
  if (!value) {
    return 'No session scheduled';
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return date.toLocaleString(undefined, {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  });
}

function Panel({
  children,
  className = '',
}: {
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <section
      className={`rounded-none border border-[#19192d]/10 bg-white ${className}`}
    >
      {children}
    </section>
  );
}

function EmptyState({ label }: { label: string }) {
  return (
    <p className='rounded-none border border-dashed border-[#19192d]/10 bg-[#fffdf9] p-6 text-sm text-[#5f6675]'>
      {label}
    </p>
  );
}

function Field({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <label className='block'>
      <span className='text-xs font-semibold uppercase tracking-[0.18em] text-[#147568]'>
        {label}
      </span>
      <div className='mt-2'>{children}</div>
    </label>
  );
}

function inputClass() {
  return 'w-full rounded-none border border-[#19192d]/10 bg-[#fffdf9] px-4 py-3 text-sm text-[#19192d] outline-none focus:border-[#147568] focus:ring-2 focus:ring-[#147568]/15';
}

function PrepText({ value }: { value?: string }) {
  if (!value) {
    return <EmptyState label='No prep details saved yet.' />;
  }

  return (
    <div className='space-y-2'>
      {value
        .split(/\n|;/)
        .map((item) => item.trim())
        .filter(Boolean)
        .map((item) => (
          <p key={item} className='text-sm leading-6 text-[#5f6675]'>
            {item}
          </p>
        ))}
    </div>
  );
}

const ClientDetail = () => {
  const router = useRouter();
  const [client, setClient] = React.useState<Client | null>(null);
  const [clientForm, setClientForm] = React.useState<ClientForm | null>(null);
  const [isSavingClient, setIsSavingClient] = React.useState(false);
  const [newActionTitle, setNewActionTitle] = React.useState('');
  const [newResourceTitle, setNewResourceTitle] = React.useState('');
  const [newResourceUrl, setNewResourceUrl] = React.useState('');
  const [notice, setNotice] = React.useState('');
  const [deletingSessionId, setDeletingSessionId] = React.useState('');
  const [clientAction, setClientAction] = React.useState('');

  React.useEffect(() => {
    if (!router.isReady || typeof router.query.clientId !== 'string') {
      return;
    }

    loadClient(router.query.clientId);
  }, [router.isReady, router.query.clientId]);

  const latestReflection = client?.prep_briefs?.find((brief) => {
    return Boolean(brief.client_reflection);
  });
  const latestPrepBrief = client?.prep_briefs?.[0];

  async function loadClient(clientId: string) {
    const response = await axios.get(`/coaching/clients/${clientId}`);
    setClient(response.data);
    setClientForm(formFromClient(response.data));
  }

  function updateClientForm(field: keyof ClientForm, value: string) {
    setClientForm((current) => {
      if (!current) {
        return current;
      }

      return {
        ...current,
        [field]: value,
      };
    });
  }

  async function saveClient() {
    if (!client || !clientForm) {
      return;
    }

    setIsSavingClient(true);
    setNotice('');

    try {
      const response = await axios.patch(`/coaching/clients/${client.id}`, {
        ...clientForm,
        next_session_at: clientForm.next_session_at || null,
      });
      setClient(response.data);
      setClientForm(formFromClient(response.data));
      setNotice('Client record saved.');
    } finally {
      setIsSavingClient(false);
    }
  }

  async function addActionItem() {
    if (!client || !newActionTitle.trim()) {
      return;
    }

    await axios.post(`/coaching/clients/${client.id}/action-items`, {
      title: newActionTitle,
    });
    setNewActionTitle('');
    await loadClient(client.id);
    setNotice('Commitment added.');
  }

  async function addResource() {
    if (!client || !newResourceTitle.trim()) {
      return;
    }

    await axios.post(`/coaching/clients/${client.id}/resources`, {
      title: newResourceTitle,
      url: newResourceUrl,
      resource_type: 'link',
      is_shared: true,
    });
    setNewResourceTitle('');
    setNewResourceUrl('');
    await loadClient(client.id);
    setNotice('Resource added and shared with client.');
  }

  async function deleteSession(session: Session) {
    const confirmed = window.confirm(
      `Delete "${session.title || 'Client session'}"? This cannot be undone.`,
    );

    if (!confirmed) {
      return;
    }

    setDeletingSessionId(session.id);
    try {
      await axios.delete(`/coaching/sessions/${session.id}`);
      setClient((currentClient) => {
        if (!currentClient) {
          return currentClient;
        }

        return {
          ...currentClient,
          sessions: (currentClient.sessions || []).filter(
            (currentSession) => currentSession.id !== session.id,
          ),
          action_items: (currentClient.action_items || []).filter(
            (actionItem) => actionItem.sessionId !== session.id,
          ),
          prep_briefs: (currentClient.prep_briefs || []).filter(
            (prepBrief) => prepBrief.sessionId !== session.id,
          ),
        };
      });

      setNotice('Session deleted.');
    } finally {
      setDeletingSessionId('');
    }
  }

  async function updateConsent(aiGranted: boolean, recordingGranted: boolean) {
    if (!client) {
      return;
    }

    setClientAction('consent');
    try {
      await axios.patch(`/coaching/clients/${client.id}/consent`, {
        ai_processing_consent_granted: aiGranted,
        recording_consent_granted: recordingGranted,
        policy_version: '2026-07-22-v1',
      });
      await loadClient(client.id);
      setNotice('Consent state updated and recorded in the audit log.');
    } finally {
      setClientAction('');
    }
  }

  async function updateReminderSettings(enabled: boolean, minutes: number | null) {
    if (!client) {
      return;
    }

    setClientAction('reminder');
    try {
      await axios.patch(`/coaching/clients/${client.id}/reminders`, {
        reminders_enabled: enabled,
        reminder_minutes: minutes,
      });
      await loadClient(client.id);
      setNotice('Client reminder settings saved.');
    } finally {
      setClientAction('');
    }
  }

  async function sendPortalInvitation() {
    if (!client) {
      return;
    }

    setClientAction('invite');
    try {
      await axios.post(`/coaching/clients/${client.id}/portal-invitation`);
      setNotice('Single-use client invitation sent.');
    } finally {
      setClientAction('');
    }
  }

  async function revokePortalAccess() {
    if (!client || !window.confirm('Revoke this client’s portal access and active invitation?')) {
      return;
    }

    setClientAction('revoke');
    try {
      await axios.delete(`/coaching/clients/${client.id}/portal-access`);
      setNotice('Portal access revoked. Existing tokens can no longer authenticate.');
    } finally {
      setClientAction('');
    }
  }

  async function exportClient() {
    if (!client) {
      return;
    }

    const response = await axios.get(`/coaching/clients/${client.id}/export`, { responseType: 'blob' });
    const url = URL.createObjectURL(response.data);
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = `client-${client.id}.json`;
    anchor.click();
    URL.revokeObjectURL(url);
    setNotice('Client export downloaded and recorded in the audit log.');
  }

  async function deleteClientPermanently() {
    if (!client) {
      return;
    }

    const confirmed = window.confirm(
      'Permanently delete this client, sessions, commitments, prep briefs, resources, portal account, intake record, and private audio? This cannot be undone.',
    );

    if (!confirmed) {
      return;
    }

    setClientAction('delete');
    try {
      await axios.delete(`/coaching/clients/${client.id}`, { data: { confirm: client.id } });
      await router.push('/clients');
    } finally {
      setClientAction('');
    }
  }

  return (
    <>
      <Head>
        <title>{getPageTitle(client?.name || 'Client')}</title>
      </Head>
      <SectionMain>
        <div className='mx-auto max-w-7xl'>
          <div className='mb-6'>
            <Link
              href='/clients'
              className='inline-flex items-center gap-2 text-sm font-semibold text-[#5f6675] hover:text-[#19192d]'
            >
              <BaseIcon path={mdiArrowLeft} size={18} />
              Clients
            </Link>
          </div>

          <div className='mb-6 flex flex-col justify-between gap-6 rounded-none bg-[#19192d] p-7 text-white md:flex-row md:items-end'>
            <div>
              <div className='flex items-center gap-3 text-[#147568]'>
                <BaseIcon path={mdiFileDocumentOutline} size={18} />
                <span className='text-xs font-semibold uppercase tracking-[0.22em]'>
                  Client file
                </span>
              </div>
              <h1 className='mt-3 text-xl font-semibold'>
                {client?.name || 'Loading client...'}
              </h1>
              <p className='mt-2 max-w-2xl text-sm leading-6 text-[#fffdf9]'>
                Edit profile context, review prep, and manage commitments and
                shared resources.
              </p>
            </div>
            <div className='flex flex-col gap-3 md:items-end'>
              {client && (
                <Link
                  href={`/start-session?clientId=${client.id}`}
                  className='inline-flex items-center justify-center gap-2 rounded-none bg-[#147568] px-4 py-2 text-sm font-semibold text-[#19192d]'
                >
                  <BaseIcon path={mdiMicrophoneOutline} size={18} />
                  Start session
                </Link>
              )}
              <div className='flex items-center gap-2 text-sm font-semibold text-[#147568]'>
                <BaseIcon path={mdiCalendarClock} size={18} />
                {displayDateTime(client?.next_session_at)}
              </div>
            </div>
          </div>

          {notice && (
            <div className='mb-4 rounded-none border border-[#147568]/20 bg-[#fffdf9] px-4 py-3 text-sm font-semibold text-[#147568]'>
              {notice}
            </div>
          )}

          {client && clientForm ? (
            <div className='space-y-6'>
              <Panel className='p-7'>
                <div className='flex flex-col justify-between gap-6 md:flex-row md:items-start'>
                  <div>
                    <p className='text-xs font-semibold uppercase tracking-[0.22em] text-[#147568]'>
                      {client.package?.title || 'Coaching client'}
                    </p>
                    <h2 className='mt-2 text-lg font-semibold text-[#19192d]'>
                      Profile
                    </h2>
                  </div>
                  <button
                    type='button'
                    className='inline-flex items-center justify-center gap-2 rounded-none bg-[#19192d] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50'
                    disabled={isSavingClient}
                    onClick={saveClient}
                  >
                    <BaseIcon path={mdiContentSaveOutline} size={18} />
                    {isSavingClient ? 'Saving...' : 'Save client'}
                  </button>
                </div>

                <div className='mt-6 grid gap-6 lg:grid-cols-4'>
                  <Field label='Name'>
                    <input
                      value={clientForm.name}
                      onChange={(event) =>
                        updateClientForm('name', event.target.value)
                      }
                      className={inputClass()}
                    />
                  </Field>
                  <Field label='Email'>
                    <input
                      value={clientForm.email}
                      type='email'
                      onChange={(event) =>
                        updateClientForm('email', event.target.value)
                      }
                      className={inputClass()}
                    />
                  </Field>
                  <Field label='Status'>
                    <select
                      value={clientForm.status}
                      onChange={(event) =>
                        updateClientForm('status', event.target.value)
                      }
                      className={inputClass()}
                    >
                      <option value='lead'>Lead</option>
                      <option value='active'>Active</option>
                      <option value='paused'>Paused</option>
                      <option value='completed'>Completed</option>
                    </select>
                  </Field>
                  <Field label='Next session'>
                    <input
                      value={clientForm.next_session_at}
                      type='datetime-local'
                      onChange={(event) =>
                        updateClientForm('next_session_at', event.target.value)
                      }
                      className={inputClass()}
                    />
                  </Field>
                  <Field label='Company'>
                    <input
                      value={clientForm.company}
                      onChange={(event) =>
                        updateClientForm('company', event.target.value)
                      }
                      className={inputClass()}
                    />
                  </Field>
                  <Field label='Role title'>
                    <input
                      value={clientForm.role_title}
                      onChange={(event) =>
                        updateClientForm('role_title', event.target.value)
                      }
                      className={inputClass()}
                    />
                  </Field>
                  <Field label='Tags'>
                    <input
                      value={clientForm.tags}
                      onChange={(event) =>
                        updateClientForm('tags', event.target.value)
                      }
                      className={inputClass()}
                    />
                  </Field>
                </div>

                <div className='mt-6 grid gap-6 lg:grid-cols-2'>
                  <Field label='Goals'>
                    <textarea
                      value={clientForm.goals}
                      rows={5}
                      onChange={(event) =>
                        updateClientForm('goals', event.target.value)
                      }
                      className={inputClass()}
                    />
                  </Field>
                  <Field label='Private coach notes'>
                    <textarea
                      value={clientForm.notes}
                      rows={5}
                      onChange={(event) =>
                        updateClientForm('notes', event.target.value)
                      }
                      className={inputClass()}
                    />
                  </Field>
                </div>
              </Panel>

              <Panel className='p-7'>
                <p className='text-xs font-semibold uppercase tracking-[0.22em] text-[#147568]'>
                  Privacy and portal access
                </p>
                <h2 className='mt-2 text-lg font-semibold text-[#19192d]'>Consent and data controls</h2>
                <p className='mt-2 max-w-3xl text-sm leading-6 text-[#5f6675]'>
                  Recording and AI processing are separate permissions. Turning either off records a withdrawal and immediately blocks that processing path. Manual coach notes remain available.
                </p>
                <div className='mt-5 grid gap-4 md:grid-cols-2'>
                  <label className='flex items-start gap-3 border border-[#19192d]/10 bg-[#fffdf9] p-4 text-sm'>
                    <input
                      type='checkbox'
                      checked={Boolean(client.recording_consent_granted)}
                      disabled={clientAction === 'consent'}
                      onChange={(event) => updateConsent(Boolean(client.ai_processing_consent_granted), event.target.checked)}
                    />
                    <span><strong>Recording authorized</strong><br />Required for microphone recording and audio upload.</span>
                  </label>
                  <label className='flex items-start gap-3 border border-[#19192d]/10 bg-[#fffdf9] p-4 text-sm'>
                    <input
                      type='checkbox'
                      checked={Boolean(client.ai_processing_consent_granted)}
                      disabled={clientAction === 'consent'}
                      onChange={(event) => updateConsent(event.target.checked, Boolean(client.recording_consent_granted))}
                    />
                    <span><strong>AI processing authorized</strong><br />Required for transcription and generated session memory.</span>
                  </label>
                </div>
                <div className='mt-5 flex flex-wrap gap-3'>
                  <button type='button' className='border border-[#19192d]/10 bg-white px-4 py-2 text-sm font-semibold' disabled={Boolean(clientAction)} onClick={sendPortalInvitation}>
                    {clientAction === 'invite' ? 'Sending...' : 'Send or resend invitation'}
                  </button>
                  <button type='button' className='border border-[#19192d]/10 bg-white px-4 py-2 text-sm font-semibold' disabled={Boolean(clientAction)} onClick={revokePortalAccess}>
                    {clientAction === 'revoke' ? 'Revoking...' : 'Revoke portal access'}
                  </button>
                  <button type='button' className='border border-[#19192d]/10 bg-white px-4 py-2 text-sm font-semibold' onClick={exportClient}>
                    Export complete record
                  </button>
                  <button type='button' className='border border-red-200 bg-white px-4 py-2 text-sm font-semibold text-red-700' disabled={Boolean(clientAction)} onClick={deleteClientPermanently}>
                    {clientAction === 'delete' ? 'Deleting...' : 'Permanently delete client'}
                  </button>
                </div>
                <div className='mt-6 flex flex-wrap items-center gap-4 border-t border-[#19192d]/10 pt-5'>
                  <label className='flex items-center gap-2 text-sm font-semibold'>
                    <input type='checkbox' checked={client.reminders_enabled !== false} disabled={clientAction === 'reminder'} onChange={(event) => updateReminderSettings(event.target.checked, client.reminder_minutes || null)} />
                    In-app session reminder
                  </label>
                  <select className='border border-[#19192d]/10 bg-white px-3 py-2 text-sm' value={client.reminder_minutes || ''} disabled={clientAction === 'reminder'} onChange={(event) => updateReminderSettings(client.reminders_enabled !== false, event.target.value ? Number(event.target.value) : null)}>
                    <option value=''>Workspace default</option>
                    <option value='10'>10 minutes before</option>
                    <option value='60'>1 hour before</option>
                    <option value='1440'>1 day before</option>
                  </select>
                </div>
              </Panel>

              <Panel>
                <div className='border-b border-[#19192d]/10 p-7'>
                  <h3 className='text-lg font-semibold text-[#19192d]'>
                    Session timeline
                  </h3>
                </div>
                <div className='overflow-x-auto'>
                  <table className='min-w-full divide-y divide-[#19192d]/10 text-left text-sm'>
                    <thead className='bg-[#fffdf9] text-xs font-semibold uppercase tracking-[0.16em] text-[#5f6675]'>
                      <tr>
                        <th className='px-5 py-3'>Session</th>
                        <th className='px-5 py-3'>Date</th>
                        <th className='px-5 py-3'>Audio</th>
                        <th className='px-5 py-3'>Status</th>
                        <th className='px-5 py-3 text-right'>Actions</th>
                      </tr>
                    </thead>
                    <tbody className='divide-y divide-[#19192d]/10'>
                      {(client.sessions || []).length > 0 ? (
                        (client.sessions || []).map((session) => (
                          <tr key={session.id} className='align-top'>
                            <td className='px-5 py-4'>
                              <p className='font-semibold text-[#19192d]'>
                                {session.title || 'Client session'}
                              </p>
                              <p className='mt-1 max-w-md truncate text-sm text-[#5f6675]'>
                                {session.ai_summary || 'No coach summary yet.'}
                              </p>
                            </td>
                            <td className='px-5 py-4 text-[#5f6675]'>
                              {displayDateTime(session.session_at)}
                            </td>
                            <td className='px-5 py-4 text-[#5f6675]'>
                              {session.audio_url ? 'Saved' : 'None'}
                            </td>
                            <td className='px-5 py-4 text-[#5f6675]'>
                              {session.status || 'completed'}
                            </td>
                            <td className='px-5 py-4'>
                              <div className='flex flex-wrap justify-end gap-2'>
                                <button
                                  type='button'
                                  className='inline-flex items-center justify-center gap-2 rounded-none border border-[#19192d]/10 bg-white px-3 py-2 text-sm font-semibold text-[#19192d]'
                                  onClick={() =>
                                    router.push(
                                      `/session-memory/view?sessionId=${session.id}`,
                                    )
                                  }
                                >
                                  <BaseIcon
                                    path={mdiFileDocumentOutline}
                                    size={18}
                                  />
                                  Open
                                </button>
                                <button
                                  type='button'
                                  className='inline-flex items-center justify-center gap-2 rounded-none border border-[#19192d]/10 bg-white px-3 py-2 text-sm font-semibold text-[#19192d] disabled:opacity-50'
                                  disabled={deletingSessionId === session.id}
                                  onClick={() => deleteSession(session)}
                                >
                                  <BaseIcon
                                    path={mdiTrashCanOutline}
                                    size={18}
                                  />
                                  {deletingSessionId === session.id
                                    ? 'Deleting...'
                                    : 'Delete'}
                                </button>
                              </div>
                            </td>
                          </tr>
                        ))
                      ) : (
                        <tr>
                          <td
                            colSpan={5}
                            className='px-5 py-8 text-center text-sm text-[#5f6675]'
                          >
                            No saved session memories yet.
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </Panel>

              <Panel>
                <div className='border-b border-[#19192d]/10 p-7'>
                  <p className='text-xs font-semibold uppercase tracking-[0.22em] text-[#147568]'>
                    Next-session prep
                  </p>
                  <h3 className='mt-2 text-lg font-semibold text-[#19192d]'>
                    Coach prep brief
                  </h3>
                </div>
                {latestPrepBrief ? (
                  <div className='grid gap-6 p-7 lg:grid-cols-2'>
                    <div className='rounded-none bg-[#fffdf9] p-6'>
                      <p className='text-xs font-semibold uppercase tracking-[0.18em] text-[#147568]'>
                        Client reflection
                      </p>
                      <div className='mt-3'>
                        <PrepText value={latestPrepBrief.client_reflection} />
                      </div>
                    </div>
                    <div className='rounded-none bg-[#fffdf9] p-6'>
                      <p className='text-xs font-semibold uppercase tracking-[0.18em] text-[#147568]'>
                        Open commitments
                      </p>
                      <div className='mt-3'>
                        <PrepText value={latestPrepBrief.open_commitments} />
                      </div>
                    </div>
                    <div className='rounded-none bg-[#fffdf9] p-6'>
                      <p className='text-xs font-semibold uppercase tracking-[0.18em] text-[#147568]'>
                        Suggested questions
                      </p>
                      <div className='mt-3'>
                        <PrepText value={latestPrepBrief.suggested_questions} />
                      </div>
                    </div>
                    <div className='rounded-none bg-[#fffdf9] p-6'>
                      <p className='text-xs font-semibold uppercase tracking-[0.18em] text-[#147568]'>
                        Watch points
                      </p>
                      <div className='mt-3'>
                        <PrepText value={latestPrepBrief.sensitive_topics} />
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className='p-7'>
                    <EmptyState label='No next-session prep brief yet. Generate session memory or ask the client for a reflection.' />
                  </div>
                )}
              </Panel>

              <div className='grid gap-6 lg:grid-cols-2'>
                <Panel>
                  <div className='border-b border-[#19192d]/10 p-7'>
                    <h3 className='text-lg font-semibold text-[#19192d]'>
                      Open commitments
                    </h3>
                  </div>
                  <div className='border-b border-[#19192d]/10 p-7'>
                    <div className='flex flex-col gap-3 md:flex-row'>
                      <input
                        value={newActionTitle}
                        onChange={(event) =>
                          setNewActionTitle(event.target.value)
                        }
                        className={inputClass()}
                        placeholder='Add a commitment before the next session'
                      />
                      <button
                        type='button'
                        className='inline-flex items-center justify-center gap-2 rounded-none bg-[#147568] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50'
                        disabled={!newActionTitle.trim()}
                        onClick={addActionItem}
                      >
                        <BaseIcon path={mdiPlus} size={18} />
                        Add
                      </button>
                    </div>
                  </div>
                  <div className='space-y-4 p-7'>
                    {(client.action_items || []).length > 0 ? (
                      (client.action_items || []).map((item) => (
                        <div
                          key={item.id}
                          className='flex gap-3 rounded-none border border-[#19192d]/10 bg-white p-6'
                        >
                          <span className='mt-0.5 grid h-8 w-8 flex-none place-items-center rounded-none bg-[#fffdf9] text-[#147568]'>
                            <BaseIcon path={mdiCheckCircleOutline} size={18} />
                          </span>
                          <div>
                            <p className='font-semibold text-[#19192d]'>
                              {item.title}
                            </p>
                            <p className='mt-1 text-sm text-[#5f6675]'>
                              {item.status.replace('_', ' ')}
                            </p>
                          </div>
                        </div>
                      ))
                    ) : (
                      <EmptyState label='No open commitments for this client.' />
                    )}
                  </div>
                </Panel>

                <Panel>
                  <div className='border-b border-[#19192d]/10 p-7'>
                    <h3 className='text-lg font-semibold text-[#19192d]'>
                      Shared resources
                    </h3>
                  </div>
                  <div className='space-y-3 border-b border-[#19192d]/10 p-7'>
                    <input
                      value={newResourceTitle}
                      onChange={(event) =>
                        setNewResourceTitle(event.target.value)
                      }
                      className={inputClass()}
                      placeholder='Resource title'
                    />
                    <input
                      value={newResourceUrl}
                      onChange={(event) =>
                        setNewResourceUrl(event.target.value)
                      }
                      className={inputClass()}
                      placeholder='https://...'
                    />
                    <button
                      type='button'
                      className='inline-flex items-center justify-center gap-2 rounded-none bg-[#147568] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50'
                      disabled={!newResourceTitle.trim()}
                      onClick={addResource}
                    >
                      <BaseIcon path={mdiPlus} size={18} />
                      Add resource
                    </button>
                  </div>
                  <div className='space-y-4 p-7'>
                    {(client.resources || []).length > 0 ? (
                      (client.resources || []).map((resource) => (
                        <a
                          key={resource.id}
                          href={resource.url || '#'}
                          target='_blank'
                          rel='noreferrer'
                          className='flex items-start gap-3 rounded-none border border-[#19192d]/10 bg-white p-6 transition hover:bg-[#fffdf9]'
                        >
                          <span className='mt-0.5 grid h-8 w-8 flex-none place-items-center rounded-none bg-[#fffdf9] text-[#147568]'>
                            <BaseIcon path={mdiLinkVariant} size={18} />
                          </span>
                          <span>
                            <span className='block font-semibold text-[#19192d]'>
                              {resource.title}
                            </span>
                            <span className='mt-1 block text-sm text-[#5f6675]'>
                              {resource.description || resource.url}
                            </span>
                          </span>
                        </a>
                      ))
                    ) : (
                      <EmptyState label='No shared resources for this client yet.' />
                    )}
                  </div>
                </Panel>
              </div>

              <div className='grid gap-6 lg:grid-cols-2'>
                <Panel>
                  <div className='border-b border-[#19192d]/10 p-7'>
                    <h3 className='text-lg font-semibold text-[#19192d]'>
                      Pre-session reflection
                    </h3>
                  </div>
                  <div className='p-7'>
                    {latestReflection ? (
                      <div className='rounded-none border border-[#19192d]/10 bg-[#fffdf9] p-6'>
                        <p className='text-sm leading-6 text-[#5f6675]'>
                          {latestReflection.client_reflection}
                        </p>
                      </div>
                    ) : (
                      <EmptyState label='No client reflection submitted yet.' />
                    )}
                  </div>
                </Panel>
              </div>
            </div>
          ) : (
            <Panel className='p-7'>
              <p className='text-sm text-[#5f6675]'>Loading client...</p>
            </Panel>
          )}
        </div>
      </SectionMain>
    </>
  );
};

ClientDetail.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default ClientDetail;
