import {
  mdiAlertCircleOutline,
  mdiArrowLeft,
  mdiChartTimelineVariant,
  mdiClipboardCheckOutline,
  mdiCurrencyUsd,
  mdiFileDocumentMultipleOutline,
  mdiMapMarkerOutline,
  mdiPencil,
  mdiProgressClock,
  mdiShieldAlertOutline,
  mdiTarget,
} from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, ReactNode, useEffect } from 'react';
import { useRouter } from 'next/router';
import dayjs from 'dayjs';
import BaseButton from '../../components/BaseButton';
import BaseButtons from '../../components/BaseButtons';
import BaseDivider from '../../components/BaseDivider';
import BaseIcon from '../../components/BaseIcon';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { humanize } from '../../helpers/humanize';
import { hasPermission } from '../../helpers/userPermissions';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { fetch } from '../../stores/projects/projectsSlice';

type RelatedColumn<T> = {
  label: string;
  render: (item: T) => ReactNode;
  className?: string;
};

const emptyValue = 'Not yet recorded';

const asArray = <T,>(value: T[] | undefined | null): T[] => (Array.isArray(value) ? value : []);

const formatDate = (value?: string | Date | null, fallback = emptyValue) => {
  if (!value) {
    return fallback;
  }

  const date = dayjs(value);
  return date.isValid() ? date.format('DD MMM YYYY') : fallback;
};

const formatDateTime = (value?: string | Date | null, fallback = emptyValue) => {
  if (!value) {
    return fallback;
  }

  const date = dayjs(value);
  return date.isValid() ? date.format('DD MMM YYYY, HH:mm') : fallback;
};

const formatCurrency = (value?: string | number | null, currency?: string | null, fallback = emptyValue) => {
  if (value === null || value === undefined || value === '') {
    return fallback;
  }

  const numericValue = Number(value);
  if (Number.isNaN(numericValue)) {
    return fallback;
  }

  const resolvedCurrency = currency || 'USD';

  return new Intl.NumberFormat(resolvedCurrency === 'CDF' ? 'fr-CD' : 'en-US', {
    style: 'currency',
    currency: resolvedCurrency,
    maximumFractionDigits: 0,
  }).format(numericValue);
};

const formatPercent = (value?: string | number | null, fallback = emptyValue) => {
  if (value === null || value === undefined || value === '') {
    return fallback;
  }

  const numericValue = Number(value);
  return Number.isNaN(numericValue) ? fallback : `${numericValue}%`;
};

const formatText = (value?: string | null, fallback = emptyValue) => (value ? humanize(value) : fallback);

const truncateText = (value?: string | null, fallback = emptyValue, length = 120) => {
  if (!value) {
    return fallback;
  }

  const normalized = value.replace(/\s+/g, ' ').trim();
  if (!normalized) {
    return fallback;
  }

  return normalized.length > length ? `${normalized.slice(0, length - 1).trimEnd()}…` : normalized;
};

const formatDateWindow = (start?: string | Date | null, end?: string | Date | null) => {
  const startLabel = formatDate(start);
  const endLabel = formatDate(end);

  if (startLabel === emptyValue && endLabel === emptyValue) {
    return emptyValue;
  }

  if (startLabel === emptyValue) {
    return `Ends ${endLabel}`;
  }

  if (endLabel === emptyValue) {
    return `Starts ${startLabel}`;
  }

  return `${startLabel} → ${endLabel}`;
};

const getBadgeClassName = (value?: string | null) => {
  switch (value) {
    case 'active':
    case 'approved':
    case 'completed':
    case 'resolved':
    case 'settled':
    case 'paid':
    case 'pass':
      return 'border-emerald-200 bg-emerald-50 text-emerald-700';
    case 'submitted':
    case 'under_review':
    case 'in_progress':
    case 'validated':
    case 'partial':
      return 'border-blue-200 bg-blue-50 text-blue-700';
    case 'on_hold':
    case 'blocked':
    case 'follow_up_required':
    case 'disputed':
    case 'partially_settled':
      return 'border-amber-200 bg-amber-50 text-amber-700';
    case 'critical':
    case 'high':
    case 'terminated':
    case 'cancelled':
    case 'closed':
    case 'fail':
      return 'border-red-200 bg-red-50 text-red-700';
    default:
      return 'border-slate-200 bg-slate-50 text-slate-700 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-200';
  }
};

const StatusBadge = ({ value, fallback = emptyValue }: { value?: string | null; fallback?: string }) => (
  <span className={`rounded-full border px-2.5 py-1 text-xs font-semibold ${getBadgeClassName(value)}`}>{formatText(value, fallback)}</span>
);

const DetailItem = ({
  label,
  value,
  fullWidth = false,
}: {
  label: string;
  value: ReactNode;
  fullWidth?: boolean;
}) => (
  <div className={fullWidth ? 'md:col-span-2' : ''}>
    <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500 dark:text-slate-400">{label}</p>
    <div className="mt-2 text-sm leading-6 text-slate-900 dark:text-slate-100">{value || emptyValue}</div>
  </div>
);

const SummaryMetric = ({
  icon,
  title,
  value,
  note,
}: {
  icon: string;
  title: string;
  value: ReactNode;
  note: string;
}) => (
  <div className="rounded-xl border border-slate-200/80 bg-slate-50/80 p-4 dark:border-dark-700 dark:bg-dark-800/60">
    <div className="flex items-start justify-between gap-3">
      <div>
        <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500 dark:text-slate-400">{title}</p>
        <p className="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">{value}</p>
      </div>
      <div className="rounded-lg border border-slate-200 bg-white p-2 text-slate-500 dark:border-dark-700 dark:bg-dark-900 dark:text-slate-300">
        <BaseIcon path={icon} size={22} />
      </div>
    </div>
    <p className="mt-3 text-sm text-slate-600 dark:text-slate-300">{note}</p>
  </div>
);

function RelatedTableCard<T>({
  title,
  description,
  rows,
  columns,
  emptyMessage,
  countLabel,
  onRowClick,
}: {
  title: string;
  description: string;
  rows: T[];
  columns: RelatedColumn<T>[];
  emptyMessage: string;
  countLabel: string;
  onRowClick?: (item: T) => void;
}) {
  return (
    <CardBox className="h-full">
      <div className="flex flex-col gap-4">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">{title}</h3>
            <p className="mt-1 text-sm text-slate-600 dark:text-slate-300">{description}</p>
            {rows.length > 0 && onRowClick && (
              <p className="mt-2 text-xs font-medium uppercase tracking-[0.15em] text-slate-500 dark:text-slate-400">Select any row to open the full record</p>
            )}
          </div>
          <span className="rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs font-semibold uppercase tracking-[0.15em] text-slate-600 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-300">
            {rows.length} {countLabel}
          </span>
        </div>

        {rows.length ? (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-slate-200 text-sm dark:divide-dark-700">
              <thead>
                <tr>
                  {columns.map((column) => (
                    <th
                      key={column.label}
                      className={`px-3 py-3 text-left text-xs font-semibold uppercase tracking-[0.15em] text-slate-500 dark:text-slate-400 ${column.className || ''}`}
                    >
                      {column.label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 dark:divide-dark-800">
                {rows.map((item, index) => (
                  <tr
                    key={(item as { id?: string }).id || index}
                    className={onRowClick ? 'cursor-pointer transition hover:bg-slate-50 dark:hover:bg-dark-800/60' : ''}
                    onClick={onRowClick ? () => onRowClick(item) : undefined}
                  >
                    {columns.map((column) => (
                      <td key={column.label} className={`px-3 py-3 align-top text-slate-700 dark:text-slate-200 ${column.className || ''}`}>
                        {column.render(item)}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50/70 px-4 py-6 text-sm text-slate-600 dark:border-dark-700 dark:bg-dark-800/50 dark:text-slate-300">
            {emptyMessage}
          </div>
        )}
      </div>
    </CardBox>
  );
}

const ProjectsView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { projects, loading } = useAppSelector((state) => state.projects);
  const { currentUser } = useAppSelector((state) => state.auth);
  const { id } = router.query;

  useEffect(() => {
    if (id) {
      dispatch(fetch({ id }));
    }
  }, [dispatch, id]);

  const project = projects && !Array.isArray(projects) ? projects : null;

  const milestoneRows = asArray(project?.project_milestones_project);
  const riskRows = asArray(project?.risks_project);
  const issueRows = asArray(project?.issues_project);
  const verificationRows = asArray(project?.field_verifications_project);
  const contractRows = asArray(project?.contracts_project);
  const invoiceRows = asArray(project?.invoices_project);
  const obligationRows = asArray(project?.obligations_project);

  return (
    <>
      <Head>
        <title>{getPageTitle('Project overview')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={project?.name || 'Project overview'}
          main
        >
          <BaseButtons type="justify-start md:justify-end" className="w-full md:w-auto" noWrap>
            <BaseButton color="white" outline icon={mdiArrowLeft} label="Back to list" onClick={() => router.push('/projects/projects-list')} />
            <BaseButton color="info" icon={mdiPencil} label="Edit project" href={`/projects/projects-edit/?id=${id}`} />
          </BaseButtons>
        </SectionTitleLineWithButton>

        <div className="space-y-6">
          <CardBox>
            <div className="flex flex-col gap-6 xl:flex-row xl:items-start xl:justify-between">
              <div className="max-w-3xl">
                <div className="flex flex-wrap items-center gap-2">
                  <span className={`rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-[0.15em] ${getBadgeClassName(project?.status)}`}>
                    {formatText(project?.status, 'Status not set')}
                  </span>
                  <span className={`rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-[0.15em] ${getBadgeClassName(project?.risk_level)}`}>
                    {project?.risk_level ? `${humanize(project.risk_level)} risk` : 'Risk not set'}
                  </span>
                </div>
                <h1 className="mt-4 text-3xl font-semibold text-slate-900 dark:text-slate-100">
                  {project?.name || 'Unnamed project'}
                </h1>
                <p className="mt-3 text-sm leading-7 text-slate-600 dark:text-slate-300">
                  {project?.objectives
                    ? 'This project page consolidates delivery context, reporting dates, financial controls, and linked operational records in one place.'
                    : 'Core project metadata is available below. Add objectives and linked records to build out the delivery picture.'}
                </p>
                <div className="mt-5 flex flex-wrap gap-6 text-sm text-slate-600 dark:text-slate-300">
                  <div>
                    <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400">Project code</p>
                    <p className="mt-2 font-medium text-slate-900 dark:text-slate-100">{project?.project_code || emptyValue}</p>
                  </div>
                  <div>
                    <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400">Province</p>
                    <p className="mt-2 font-medium text-slate-900 dark:text-slate-100">{project?.province?.name || emptyValue}</p>
                  </div>
                  <div>
                    <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400">Reporting cycle</p>
                    <p className="mt-2 font-medium text-slate-900 dark:text-slate-100">{project?.reporting_cycle || emptyValue}</p>
                  </div>
                </div>
              </div>

              <div className="grid w-full gap-4 md:grid-cols-2 xl:max-w-xl">
                <SummaryMetric
                  icon={mdiProgressClock}
                  title="Completion"
                  value={formatPercent(project?.completion_percent, '0%')}
                  note="Use this to track delivery progress against the plan."
                />
                <SummaryMetric
                  icon={mdiCurrencyUsd}
                  title="Planned budget"
                  value={formatCurrency(project?.planned_budget, project?.currency)}
                  note="Approved planning figure for this project record."
                />
                <SummaryMetric
                  icon={mdiAlertCircleOutline}
                  title="Open risks"
                  value={riskRows.length}
                  note="Linked project risks that may require mitigation or review."
                />
                <SummaryMetric
                  icon={mdiFileDocumentMultipleOutline}
                  title="Linked contracts"
                  value={contractRows.length}
                  note="Commercial agreements currently associated with this project."
                />
              </div>
            </div>
          </CardBox>

          <div className="grid gap-6 xl:grid-cols-3">
            <CardBox className="xl:col-span-2">
              <div>
                <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">Project profile</h2>
                <p className="mt-1 text-sm text-slate-600 dark:text-slate-300">
                  Core ownership, scope, and reporting information for this project.
                </p>
                <div className="mt-6 grid gap-6 md:grid-cols-2">
                  {hasPermission(currentUser, 'READ_ORGANIZATIONS') && (
                    <DetailItem label="Organization" value={project?.organization?.name || emptyValue} />
                  )}
                  <DetailItem label="Program" value={project?.program?.name || emptyValue} />
                  <DetailItem label="Province" value={project?.province?.name || emptyValue} />
                  <DetailItem label="Budget line" value={project?.budget_line?.name || emptyValue} />
                  <DetailItem label="Implementing entity" value={project?.implementing_entity || emptyValue} />
                  <DetailItem label="Last reported" value={formatDateTime(project?.last_reported_at)} />
                </div>
              </div>
            </CardBox>

            <CardBox>
              <div>
                <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">Delivery window</h2>
                <p className="mt-1 text-sm text-slate-600 dark:text-slate-300">
                  Schedule, risk posture, and financial baseline at a glance.
                </p>
                <div className="mt-6 space-y-5">
                  <div className="flex items-start gap-3">
                    <div className="mt-0.5 rounded-lg border border-slate-200 bg-slate-50 p-2 text-slate-500 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-300">
                      <BaseIcon path={mdiMapMarkerOutline} size={20} />
                    </div>
                    <div>
                      <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400">Timeline</p>
                      <p className="mt-2 text-sm font-medium text-slate-900 dark:text-slate-100">
                        {formatDate(project?.start_date)} → {formatDate(project?.end_date)}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-start gap-3">
                    <div className="mt-0.5 rounded-lg border border-slate-200 bg-slate-50 p-2 text-slate-500 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-300">
                      <BaseIcon path={mdiShieldAlertOutline} size={20} />
                    </div>
                    <div>
                      <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400">Risk level</p>
                      <p className="mt-2 text-sm font-medium text-slate-900 dark:text-slate-100">{formatText(project?.risk_level, 'Risk not set')}</p>
                    </div>
                  </div>
                  <div className="flex items-start gap-3">
                    <div className="mt-0.5 rounded-lg border border-slate-200 bg-slate-50 p-2 text-slate-500 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-300">
                      <BaseIcon path={mdiTarget} size={20} />
                    </div>
                    <div>
                      <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400">Execution baseline</p>
                      <p className="mt-2 text-sm font-medium text-slate-900 dark:text-slate-100">
                        {formatCurrency(project?.planned_budget, project?.currency)} · {project?.currency || 'Currency not set'}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </CardBox>
          </div>

          <CardBox>
            <div>
              <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">Objectives</h2>
              <p className="mt-1 text-sm text-slate-600 dark:text-slate-300">
                Strategic purpose and expected delivery outcomes for the project.
              </p>
              <BaseDivider />
              {project?.objectives ? (
                <div
                  className="text-sm leading-7 text-slate-700 dark:text-slate-200 [&_p]:mb-4 [&_ul]:ml-5 [&_ul]:list-disc [&_ol]:ml-5 [&_ol]:list-decimal"
                  dangerouslySetInnerHTML={{ __html: project.objectives }}
                />
              ) : (
                <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50/70 px-4 py-6 text-sm text-slate-600 dark:border-dark-700 dark:bg-dark-800/50 dark:text-slate-300">
                  Objectives have not been documented for this project yet.
                </div>
              )}
            </div>
          </CardBox>

          <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-4">
            <SummaryMetric icon={mdiClipboardCheckOutline} title="Milestones" value={milestoneRows.length} note="Delivery checkpoints linked to this project." />
            <SummaryMetric icon={mdiShieldAlertOutline} title="Risks" value={riskRows.length} note="Tracked risks requiring monitoring or mitigation." />
            <SummaryMetric icon={mdiAlertCircleOutline} title="Issues" value={issueRows.length} note="Execution issues logged against the project." />
            <SummaryMetric icon={mdiFileDocumentMultipleOutline} title="Invoices & obligations" value={invoiceRows.length + obligationRows.length} note="Financial execution records captured on the project." />
          </div>

          <div className="grid gap-6 xl:grid-cols-2">
            <RelatedTableCard
              title="Milestones"
              description="Planned and actual delivery checkpoints for this project."
              rows={milestoneRows}
              countLabel="records"
              emptyMessage="No milestones are linked to this project yet."
              onRowClick={(item: any) => router.push(`/project_milestones/project_milestones-view/?id=${item.id}`)}
              columns={[
                {
                  label: 'Milestone',
                  render: (item: any) => (
                    <div className="max-w-sm">
                      <p className="font-medium text-slate-900 dark:text-slate-100">{item.name || 'Untitled milestone'}</p>
                      <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">{truncateText(item.description, 'No delivery note recorded', 110)}</p>
                    </div>
                  ),
                },
                { label: 'Progress', render: (item: any) => <StatusBadge value={item.status} fallback="Status not set" /> },
                {
                  label: 'Schedule',
                  render: (item: any) => (
                    <div>
                      <p>{formatDateWindow(item.planned_start_date, item.planned_end_date)}</p>
                      <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">Actual close: {formatDate(item.actual_end_date)}</p>
                    </div>
                  ),
                },
                { label: 'Weight', render: (item: any) => formatPercent(item.weight_percent) },
              ]}
            />

            <RelatedTableCard
              title="Risks"
              description="Current project risks with review dates and mitigation status."
              rows={riskRows}
              countLabel="records"
              emptyMessage="No risks are linked to this project yet."
              onRowClick={(item: any) => router.push(`/risks/risks-view/?id=${item.id}`)}
              columns={[
                {
                  label: 'Risk',
                  render: (item: any) => (
                    <div className="max-w-sm">
                      <p className="font-medium text-slate-900 dark:text-slate-100">{item.title || 'Untitled risk'}</p>
                      <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">{truncateText(item.description, 'No risk note recorded', 110)}</p>
                    </div>
                  ),
                },
                { label: 'Category', render: (item: any) => formatText(item.category, 'Category not set') },
                { label: 'Exposure', render: (item: any) => <StatusBadge value={item.impact} fallback="Impact not set" /> },
                { label: 'Review date', render: (item: any) => formatDate(item.review_due_at) },
              ]}
            />

            <RelatedTableCard
              title="Issues"
              description="Execution issues currently tracked for the project."
              rows={issueRows}
              countLabel="records"
              emptyMessage="No issues are linked to this project yet."
              onRowClick={(item: any) => router.push(`/issues/issues-view/?id=${item.id}`)}
              columns={[
                {
                  label: 'Issue',
                  render: (item: any) => (
                    <div className="max-w-sm">
                      <p className="font-medium text-slate-900 dark:text-slate-100">{item.title || 'Untitled issue'}</p>
                      <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">{truncateText(item.description, 'No issue note recorded', 110)}</p>
                    </div>
                  ),
                },
                { label: 'Severity', render: (item: any) => <StatusBadge value={item.severity} fallback="Severity not set" /> },
                { label: 'Resolution', render: (item: any) => <StatusBadge value={item.status} fallback="Status not set" /> },
                { label: 'Target date', render: (item: any) => formatDate(item.due_at) },
              ]}
            />

            <RelatedTableCard
              title="Field verifications"
              description="Verification activity and follow-up actions completed in the field."
              rows={verificationRows}
              countLabel="records"
              emptyMessage="No field verifications are linked to this project yet."
              onRowClick={(item: any) => router.push(`/field_verifications/field_verifications-view/?id=${item.id}`)}
              columns={[
                {
                  label: 'Verification',
                  render: (item: any) => (
                    <div className="max-w-sm">
                      <p className="font-medium text-slate-900 dark:text-slate-100">{formatText(item.verification_type, 'Verification type not set')}</p>
                      <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">{truncateText(item.findings, 'No findings recorded', 110)}</p>
                    </div>
                  ),
                },
                { label: 'Outcome', render: (item: any) => <StatusBadge value={item.outcome} fallback="Outcome not set" /> },
                { label: 'Visit date', render: (item: any) => formatDate(item.visit_date) },
                { label: 'Reported at', render: (item: any) => formatDateTime(item.createdAt) },
              ]}
            />

            <RelatedTableCard
              title="Contracts"
              description="Commercial agreements and delivery commitments tied to this project."
              rows={contractRows}
              countLabel="records"
              emptyMessage="No contracts are linked to this project yet."
              onRowClick={(item: any) => router.push(`/contracts/contracts-view/?id=${item.id}`)}
              columns={[
                {
                  label: 'Contract',
                  render: (item: any) => (
                    <div className="max-w-sm">
                      <p className="font-medium text-slate-900 dark:text-slate-100">{item.title || item.contract_number || 'Untitled contract'}</p>
                      <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">{item.contract_number || 'No contract number'}{item.vendor?.name ? ` · ${item.vendor.name}` : ''}</p>
                    </div>
                  ),
                },
                { label: 'Type', render: (item: any) => formatText(item.contract_type, 'Type not set') },
                { label: 'Contract value', render: (item: any) => formatCurrency(item.contract_value, item.currency) },
                { label: 'End date', render: (item: any) => formatDate(item.end_date) },
              ]}
            />

            <RelatedTableCard
              title="Invoices"
              description="Invoice flow and payment readiness associated with this project."
              rows={invoiceRows}
              countLabel="records"
              emptyMessage="No invoices are linked to this project yet."
              onRowClick={(item: any) => router.push(`/invoices/invoices-view/?id=${item.id}`)}
              columns={[
                {
                  label: 'Invoice',
                  render: (item: any) => (
                    <div>
                      <p className="font-medium text-slate-900 dark:text-slate-100">{item.invoice_number || 'Invoice without number'}</p>
                      <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">Issued {formatDate(item.invoice_date)}</p>
                    </div>
                  ),
                },
                { label: 'Invoice total', render: (item: any) => formatCurrency(item.total_amount, item.currency) },
                { label: 'Payment status', render: (item: any) => <StatusBadge value={item.status} fallback="Status not set" /> },
                { label: 'Due date', render: (item: any) => formatDate(item.due_date) },
              ]}
            />
          </div>

          <RelatedTableCard
            title="Obligations"
            description="Recorded obligations and commitment timing against the project budget."
            rows={obligationRows}
            countLabel="records"
            emptyMessage="No obligations are linked to this project yet."
            onRowClick={(item: any) => router.push(`/obligations/obligations-view/?id=${item.id}`)}
            columns={[
              {
                label: 'Obligation',
                render: (item: any) => (
                  <div className="max-w-sm">
                    <p className="font-medium text-slate-900 dark:text-slate-100">{item.obligation_number || 'Obligation without number'}</p>
                    <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">{truncateText(item.notes, 'No notes recorded', 110)}</p>
                  </div>
                ),
              },
              { label: 'Committed amount', render: (item: any) => formatCurrency(item.amount, item.currency) },
              { label: 'Commitment status', render: (item: any) => <StatusBadge value={item.status} fallback="Status not set" /> },
              { label: 'Recorded at', render: (item: any) => formatDateTime(item.obligated_at) },
            ]}
          />

          <BaseDivider />

          <div className="flex flex-wrap gap-3">
            <BaseButton color="white" outline icon={mdiArrowLeft} label="Back to list" onClick={() => router.push('/projects/projects-list')} />
            <BaseButton color="info" icon={mdiPencil} label="Edit project" href={`/projects/projects-edit/?id=${id}`} />
          </div>

          {!project && !loading && (
            <CardBox>
              <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50/70 px-4 py-6 text-sm text-slate-600 dark:border-dark-700 dark:bg-dark-800/50 dark:text-slate-300">
                Project details could not be loaded for this record.
              </div>
            </CardBox>
          )}
        </div>
      </SectionMain>
    </>
  );
};

ProjectsView.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission={'READ_PROJECTS'}>{page}</LayoutAuthenticated>;
};

export default ProjectsView;
