import { baseAPI } from "@/lib/api";

export const recordTypes = {
  "progress-reports": ["Progress reports", "របាយការណ៍វឌ្ឍនភាព"],
  issues: ["Issues", "បញ្ហា"],
  "meeting-requests": ["Meeting requests", "សំណើប្រជុំ"],
  meetings: ["Meetings", "កិច្ចប្រជុំ"],
  "meeting-summaries": ["Meeting summaries", "សេចក្តីសង្ខេបកិច្ចប្រជុំ"],
  plenaries: ["Plenaries", "កិច្ចប្រជុំពេញអង្គ"],
  "rgc-decisions": ["RGC decisions", "សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល"],
  users: ["Users", "អ្នកប្រើប្រាស់"],
  roles: ["Roles", "តួនាទី"],
  permissions: ["Permissions", "សិទ្ធិ"],
  stakeholders: ["Stakeholders", "ស្ថាប័ន"],
  "stakeholder-types": ["Stakeholder types", "ប្រភេទស្ថាប័ន"],
  categories: ["Issue categories", "ប្រភេទបញ្ហា"],
  "issue-statuses": ["Issue statuses", "ស្ថានភាពបញ្ហា"],
  indicators: ["Indicators", "សូចនាករ"],
  "comment-types": ["Comment types", "ប្រភេទមតិយោបល់"],
} as const;
export type RecordType = keyof typeof recordTypes;
export type DeletedRecord = {
  id: number;
  type: RecordType;
  title: string;
  deletedAt: string;
  createdAt: string;
  deletedBy: { id: number; name: string } | null;
  details: Record<string, unknown>;
};
export type LinkedRecord = {
  id: number;
  type: string;
  title: string;
  khName?: string | null;
  deleted: boolean;
};
export type RecordDetail = DeletedRecord & {
  parents: LinkedRecord[];
  assignments: LinkedRecord[];
  relatedCounts: { type: string; total: number; deleted: number }[];
};
export type RecordFilters = {
  type: RecordType | "all";
  search: string;
  from: Date | null;
  to: Date | null;
};

export function listRecycleBinRecords(
  filters: RecordFilters,
  page: number,
  signal?: AbortSignal,
): Promise<{ data: DeletedRecord[]; meta: { total: number } }> {
  const query = new URLSearchParams({
    type: filters.type,
    search: filters.search,
    page: String(page + 1),
    limit: "25",
  });
  if (filters.from && Number.isFinite(filters.from.getTime())) {
    const start = new Date(filters.from);
    start.setHours(0, 0, 0, 0);
    query.set("deletedFrom", start.toISOString());
  }
  if (filters.to && Number.isFinite(filters.to.getTime())) {
    const end = new Date(filters.to);
    end.setHours(23, 59, 59, 999);
    query.set("deletedTo", end.toISOString());
  }
  return baseAPI(`/admin/recycle-bin?${query}`, { signal });
}
export async function getRecycleBinRecord(
  row: DeletedRecord,
  signal?: AbortSignal,
): Promise<RecordDetail> {
  const response: { data: RecordDetail } = await baseAPI(
    `/admin/recycle-bin/${row.type}/${row.id}`,
    { signal },
  );
  return response.data;
}
export function restoreRecycleBinRecord(
  row: DeletedRecord,
  language: string,
): Promise<unknown> {
  return baseAPI(`/admin/recycle-bin/${row.type}/${row.id}/restore`, {
    method: "POST",
    headers: { "Accept-Language": language === "kh" ? "km" : "en" },
  });
}

export function permanentlyDeleteRecycleBinRecord(
  row: DeletedRecord,
  language: string,
): Promise<unknown> {
  return baseAPI(`/admin/recycle-bin/${row.type}/${row.id}`, {
    method: "DELETE",
    headers: { "Accept-Language": language === "kh" ? "km" : "en" },
  });
}

export const binText = {
  en: {
    title: "Recycle Bin",
    type: "Record type",
    search: "Search ID or name",
    from: "Deleted from",
    to: "Deleted through",
    reset: "Reset",
    id: "Record ID",
    name: "Title / name",
    deleted: "Deleted at",
    deletedBy: "Deleted by",
    unknown: "Unknown",
    created: "Created at",
    actions: "Actions",
    view: "View details",
    restore: "Restore",
    permanentlyDelete: "Delete permanently",
    permanentDeleteConfirm: "Permanently delete this record?",
    permanentDeleteDescription:
      "This record, its owned details and association links will be permanently deleted and cannot be restored. Shared records will be kept, and optional links will be cleared. Required shared links must be reassigned first. Uploaded files and activity history will be kept.",
    issuePermanentDeleteDescription:
      "This issue, its owned comments, evaluations, resolution details and association links will be permanently deleted and cannot be restored. Its category, status, agencies, users, meetings, RGC decisions and progress reports will be kept. Optional report links will be cleared. Uploaded files and activity history will be kept.",
    reportPermanentDeleteDescription:
      "This progress report and its deadlines, meeting entries, submissions, document records, updates, comments, evaluations and dashboard snapshots will be permanently deleted and cannot be restored. Shared issues, RGC decisions, ministries, users and other reports will be kept. Uploaded files are not removed from storage.",
    permanentDeleteAccess:
      "Account data and access assignments belonging to this record will be removed. Shared users, roles and permissions will not be deleted. Other assigned users may lose access when a role or permission is deleted.",
    permanentDeleteSuccess: "Record permanently deleted successfully.",
    permanentDeleteFailed: "Unable to permanently delete this record.",
    cancel: "Cancel",
    close: "Close",
    empty: "No deleted records found.",
    loading: "Loading",
    error: "Unable to load deleted records.",
    retry: "Retry",
    denied: "Only administrators can access deleted records.",
    success: "Record restored successfully.",
    failed: "Unable to restore this record.",
    confirm: "Restore this record?",
    description:
      "The original ID and status will be preserved. Other deleted records will not be restored automatically.",
    access:
      "Existing role and permission assignments will be preserved. Restoring a role or permission can restore access for its assigned users.",
    user: "This user will remain inactive. Activate the account separately in User Management when ready.",
    linked: "Related records",
    assignments: "Existing assignments",
    deletedLabel: "Deleted",
    active: "Active",
    parentWarning: "Restore deleted related records first.",
    invalidDates: "The start date must not be after the end date.",
    yes: "Yes",
    no: "No",
  },
  kh: {
    title: "ទិន្នន័យដែលបានលុប",
    permanentlyDelete: "លុបជាអចិន្ត្រៃយ៍",
    permanentDeleteConfirm: "លុបទិន្នន័យនេះជាអចិន្ត្រៃយ៍?",
    permanentDeleteDescription:
      "ទិន្នន័យនេះ រួមទាំងព័ត៌មានលម្អិត និងការភ្ជាប់ដែលជារបស់វា នឹងត្រូវបានលុបជាអចិន្ត្រៃយ៍ ហើយមិនអាចស្ដារឡើងវិញបានទេ។ ទិន្នន័យរួមនឹងត្រូវរក្សាទុក ហើយការភ្ជាប់ដែលមិនចាំបាច់នឹងត្រូវដកចេញ។ ការភ្ជាប់រួមដែលចាំបាច់ ត្រូវប្ដូរទៅទិន្នន័យផ្សេងជាមុន។ ឯកសារដែលបានផ្ទុកឡើង និងប្រវត្តិសកម្មភាពនឹងត្រូវរក្សាទុក។",
    issuePermanentDeleteDescription:
      "បញ្ហានេះ រួមទាំងមតិយោបល់ ការវាយតម្លៃ ព័ត៌មានដំណោះស្រាយ និងការភ្ជាប់ដែលជារបស់វា នឹងត្រូវបានលុបជាអចិន្ត្រៃយ៍ ហើយមិនអាចស្ដារឡើងវិញបានទេ។ ប្រភេទបញ្ហា ស្ថានភាព ស្ថាប័ន អ្នកប្រើប្រាស់ កិច្ចប្រជុំ សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល និងរបាយការណ៍វឌ្ឍនភាព នឹងត្រូវរក្សាទុក។ ការភ្ជាប់របាយការណ៍ដែលមិនចាំបាច់នឹងត្រូវដកចេញ។ ឯកសារដែលបានផ្ទុកឡើង និងប្រវត្តិសកម្មភាពនឹងត្រូវរក្សាទុក។",
    reportPermanentDeleteDescription:
      "របាយការណ៍វឌ្ឍនភាពនេះ រួមទាំងកាលកំណត់ កិច្ចប្រជុំ ការដាក់ស្នើ ទិន្នន័យឯកសារ បច្ចុប្បន្នភាព មតិយោបល់ ការវាយតម្លៃ និងទិន្នន័យផ្ទាំងគ្រប់គ្រងរបស់វា នឹងត្រូវបានលុបជាអចិន្ត្រៃយ៍ ហើយមិនអាចស្ដារឡើងវិញបានទេ។ បញ្ហា សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល ក្រសួង អ្នកប្រើប្រាស់ និងរបាយការណ៍ផ្សេងទៀត នឹងត្រូវរក្សាទុក។ ឯកសារដែលបានផ្ទុកឡើងនឹងមិនត្រូវបានលុបចេញពីកន្លែងផ្ទុកទេ។",
    permanentDeleteAccess:
      "ព័ត៌មានគណនី និងការកំណត់សិទ្ធិដែលជារបស់ទិន្នន័យនេះនឹងត្រូវដកចេញ។ អ្នកប្រើប្រាស់ តួនាទី និងសិទ្ធិរួម នឹងមិនត្រូវបានលុបទេ។ ការលុបតួនាទី ឬសិទ្ធិ អាចធ្វើឱ្យអ្នកប្រើប្រាស់ដែលបានកំណត់បាត់បង់សិទ្ធិចូលប្រើ។",
    permanentDeleteSuccess: "បានលុបទិន្នន័យជាអចិន្ត្រៃយ៍ដោយជោគជ័យ។",
    permanentDeleteFailed: "មិនអាចលុបទិន្នន័យនេះជាអចិន្ត្រៃយ៍បានទេ។",
    deletedBy: "លុបដោយ",
    unknown: "មិនស្គាល់",
    type: "ប្រភេទទិន្នន័យ",
    search: "ស្វែងរកលេខសម្គាល់ ឬឈ្មោះ",
    from: "បានលុបចាប់ពី",
    to: "បានលុបរហូតដល់",
    reset: "កំណត់ឡើងវិញ",
    id: "លេខសម្គាល់",
    name: "ចំណងជើង / ឈ្មោះ",
    deleted: "កាលបរិច្ឆេទលុប",
    created: "កាលបរិច្ឆេទបង្កើត",
    actions: "សកម្មភាព",
    view: "មើលលម្អិត",
    restore: "ស្ដារ",
    cancel: "បោះបង់",
    close: "បិទ",
    empty: "មិនមានទិន្នន័យដែលបានលុបទេ។",
    loading: "កំពុងផ្ទុក",
    error: "មិនអាចផ្ទុកទិន្នន័យដែលបានលុបបានទេ។",
    retry: "ព្យាយាមម្ដងទៀត",
    denied: "មានតែអ្នកគ្រប់គ្រងប៉ុណ្ណោះដែលអាចមើលទិន្នន័យដែលបានលុប។",
    success: "បានស្ដារទិន្នន័យដោយជោគជ័យ។",
    failed: "មិនអាចស្ដារទិន្នន័យនេះបានទេ។",
    confirm: "ស្ដារទិន្នន័យនេះវិញ?",
    description:
      "លេខសម្គាល់ និងស្ថានភាពដើមនឹងត្រូវបានរក្សាទុក។ ទិន្នន័យផ្សេងទៀតដែលបានលុបនឹងមិនត្រូវបានស្ដារដោយស្វ័យប្រវត្តិទេ។",
    access:
      "ការកំណត់តួនាទី និងសិទ្ធិដើមនឹងត្រូវបានរក្សាទុក។ ការស្ដារតួនាទី ឬសិទ្ធិអាចផ្ដល់សិទ្ធិចូលប្រើឡើងវិញដល់អ្នកប្រើប្រាស់ដែលពាក់ព័ន្ធ។",
    user: "អ្នកប្រើប្រាស់នេះនឹងនៅតែអសកម្ម។ សូមបើកដំណើរការគណនីនៅក្នុងការគ្រប់គ្រងអ្នកប្រើប្រាស់ពេលរួចរាល់។",
    linked: "ទិន្នន័យដែលពាក់ព័ន្ធ",
    assignments: "ការកំណត់ដែលមានស្រាប់",
    deletedLabel: "បានលុប",
    active: "សកម្ម",
    parentWarning: "សូមស្ដារទិន្នន័យដែលពាក់ព័ន្ធដែលបានលុបជាមុន។",
    invalidDates: "កាលបរិច្ឆេទចាប់ផ្ដើមមិនត្រូវក្រោយកាលបរិច្ឆេទបញ្ចប់ទេ។",
    yes: "បាទ/ចាស",
    no: "ទេ",
  },
};

export const fieldLabels: Record<string, [string, string]> = {
  submissions: ["Ministry submissions", "របាយការណ៍របស់ក្រសួង"],
  deadlines: ["Deadlines", "កាលកំណត់"],
  dashboards: ["Dashboards", "ផ្ទាំងគ្រប់គ្រង"],
  "issue-updates": ["Issue updates", "បច្ចុប្បន្នភាពបញ្ហា"],
  title: ["Title", "ចំណងជើង"],
  name: ["Name", "ឈ្មោះ"],
  kh_name: ["Khmer name", "ឈ្មោះជាភាសាខ្មែរ"],
  number_issue: ["Issue ID", "លេខសម្គាល់បញ្ហា"],
  description: ["Description", "ការពិពណ៌នា"],
  recommendation: ["Recommendation", "អនុសាសន៍"],
  attachment: ["Attachment", "ឯកសារភ្ជាប់"],
  status: ["Status", "ស្ថានភាព"],
  meeting_date: ["Meeting date", "កាលបរិច្ឆេទប្រជុំ"],
  location: ["Location", "ទីតាំង"],
  document_reference: ["Document", "ឯកសារ"],
  meeting_request_letter: ["Request letter", "លិខិតស្នើសុំ"],
  share: ["Shared", "បានចែករំលែក"],
  deadline: ["Deadline", "ថ្ងៃផុតកំណត់"],
  decision: ["RGC decision", "សេចក្តីសម្រេចរបស់រាជរដ្ឋាភិបាល"],
  focal_person: ["Focal person", "មន្ត្រីទទួលបន្ទុក"],
  verification_source: ["Verification source", "ប្រភពផ្ទៀងផ្ទាត់"],
  verification_link: ["Verification link", "តំណភ្ជាប់ផ្ទៀងផ្ទាត់"],
  submitted_to_cdc_at: ["Submitted at", "កាលបរិច្ឆេទដាក់ស្នើ"],
  year: ["Year", "ឆ្នាំ"],
  semester: ["Semester", "ឆមាស"],
  draft_semester_report: ["Draft report", "របាយការណ៍ព្រាង"],
  final_semester_report: ["Final report", "របាយការណ៍ចុងក្រោយ"],
  email: ["Email", "អ៊ីមែល"],
  is_active: ["Active", "សកម្ម"],
  active: ["Active", "សកម្ម"],
  guard_name: ["Guard", "ប្រព័ន្ធផ្ទៀងផ្ទាត់"],
  code: ["Code", "កូដ"],
};

export const valueLabels: Record<string, [string, string]> = {
  DRAFT: ["Draft", "ព្រាង"],
  SENT: ["Sent", "បានផ្ញើ"],
  SUBMITTED: ["Submitted", "បានដាក់ស្នើ"],
  UNDER_REVIEW: ["Under review", "កំពុងពិនិត្យ"],
  SCHEDULED: ["Scheduled", "បានកំណត់កាលបរិច្ឆេទ"],
  COMPLETED: ["Completed", "បានបញ្ចប់"],
  NOT_ADDRESSED: ["Not addressed", "មិនទាន់ដោះស្រាយ"],
  IN_PROGRESS: ["In progress", "កំពុងដោះស្រាយ"],
  SOLVED: ["Solved", "បានដោះស្រាយ"],
  S1: ["S1", "ឆមាសទី១"],
  S2: ["S2", "ឆមាសទី២"],
};

// Rich text is displayed as text, never injected as HTML.
export function plainValue(value: unknown): string {
  if (value == null) return "—";
  if (typeof value === "string")
    return value
      .replace(/<[^>]*>/g, " ")
      .replace(/\s+/g, " ")
      .trim();
  if (typeof value === "number" || typeof value === "boolean")
    return String(value);
  if (Array.isArray(value)) return value.map(plainValue).join(" ");
  if (typeof value === "object") {
    const richText = value as { text?: unknown; content?: unknown };
    return plainValue(richText.text ?? richText.content);
  }
  return "—";
}
