import { calculateReportScore, getEntryTime } from "./scoring";
import { summarizeVerification, verifyEntryIntegrity } from "./integrity";
import type { EvaluatorNote, EvaluatorProfile, ExportPayload, ImportTargetResolution, Report, StoredEntry } from "./types";

const EVALUATOR_KEY = "arbeidsevne-egenvurdering:evaluator-profiles";

export type ImportResult = {
  profile: EvaluatorProfile;
  added: number;
  skipped: number;
  verification: ReturnType<typeof summarizeVerification>;
  target_resolution: ImportTargetResolution;
  matched_person_id: string | null;
  matched_report_ids: string[];
};

function readProfiles(): EvaluatorProfile[] {
  const raw = localStorage.getItem(EVALUATOR_KEY);
  if (!raw) return [];

  try {
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}

function writeProfiles(profiles: EvaluatorProfile[]) {
  localStorage.setItem(EVALUATOR_KEY, JSON.stringify(profiles));
}

export function listEvaluatorProfiles() {
  return readProfiles().map(normalizeProfile).sort((a, b) => b.updated_at.localeCompare(a.updated_at));
}

export function updateEvaluatorProfile(profile: EvaluatorProfile) {
  const profiles = readProfiles();
  const next = profiles.some((item) => item.id === profile.id)
    ? profiles.map((item) => (item.id === profile.id ? profile : item))
    : [profile, ...profiles];
  writeProfiles(next);
}

export function renameEvaluatorProfile(profileId: string, displayName: string) {
  const now = new Date().toISOString();
  const profiles = readProfiles().map((profile) =>
    profile.id === profileId ? { ...profile, display_name: displayName.trim() || profile.display_name, updated_at: now } : profile
  );
  writeProfiles(profiles);
}

export function deleteEvaluatorProfile(profileId: string) {
  writeProfiles(readProfiles().filter((profile) => profile.id !== profileId));
}

export function addEvaluatorNote(profileId: string, text: string, relatedReportId?: string) {
  return upsertEvaluatorNote(profileId, text, { note_type: relatedReportId ? "report" : "person", related_report_id: relatedReportId });
}

export function upsertEvaluatorNote(
  profileId: string,
  text: string,
  noteTarget: Pick<EvaluatorNote, "note_type" | "related_report_id" | "related_followup_id" | "parent_report_id">
) {
  const now = new Date().toISOString();
  const trimmed = text.trim();
  const profiles = readProfiles().map((profile) =>
    profile.id === profileId ? upsertNoteInProfile(normalizeProfile(profile), trimmed, noteTarget, now) : profile
  );
  writeProfiles(profiles);
}

export function deleteEvaluatorNote(
  profileId: string,
  noteTarget: Pick<EvaluatorNote, "note_type" | "related_report_id" | "related_followup_id">
) {
  const now = new Date().toISOString();
  const profiles = readProfiles().map((profile) =>
    profile.id === profileId
      ? {
          ...normalizeProfile(profile),
          evaluator_notes: normalizeProfile(profile).evaluator_notes.filter((note) => !sameNoteTarget(note, noteTarget)),
          updated_at: now
        }
      : profile
  );
  writeProfiles(profiles);
}

export function importExportPayload(jsonText: string, displayName: string, targetProfileId?: string): ImportResult {
  const reports = extractReports(JSON.parse(jsonText)).map(verifyEntryIntegrity);
  const profiles = readProfiles().map(normalizeProfile);
  const fingerprint = makeFingerprint(reports);
  const target = resolveImportTarget(reports, profiles, targetProfileId);
  if (target.action === "conflict_requires_manual_resolution") {
    const names = target.matches.map((match) => `${match.person.display_name} (${match.matchCount})`).join(", ");
    throw new Error(`Importen matcher flere brukere og må avklares manuelt: ${names}.`);
  }
  const targetProfile = target.person;
  const now = new Date().toISOString();

  const existingReports = targetProfile?.reports ?? [];
  const existingKeys = new Set(existingReports.map(reportSignature));
  const nextReports: StoredEntry[] = [...existingReports];
  let added = 0;
  let skipped = 0;

  for (const report of reports) {
    const normalized = normalizeImportedEntry(report);
    const signature = reportSignature(normalized);
    if (existingKeys.has(signature)) {
      skipped += 1;
      continue;
    }
    existingKeys.add(signature);
    nextReports.push(normalized);
    added += 1;
  }

  const profile: EvaluatorProfile = targetProfile
    ? {
        ...targetProfile,
        display_name: targetProfile.display_name,
        updated_at: now,
        source_fingerprint: targetProfile.source_fingerprint ?? fingerprint,
        reports: nextReports.sort((a, b) => getEntryTime(b) - getEntryTime(a))
      }
    : {
        id: crypto.randomUUID(),
        display_name: displayName.trim() || `Import ${new Date().toLocaleDateString("nb-NO")}`,
        created_at: now,
        updated_at: now,
        source_fingerprint: fingerprint,
        reports: nextReports.sort((a, b) => getEntryTime(b) - getEntryTime(a)),
        evaluator_notes: []
      };

  updateEvaluatorProfile(profile);
  return {
    profile,
    added,
    skipped,
    verification: summarizeVerification(reports),
    target_resolution: targetProfile ? "matched_existing_person" : "created_new_person",
    matched_person_id: targetProfile?.id ?? null,
    matched_report_ids: target.matchedReportIds
  };
}

export function exportEvaluatorBackup() {
  return JSON.stringify(
    {
      backup_type: "arbeidsevne-veilederdata",
      schema_version: 1,
      exported_at: new Date().toISOString(),
      profiles: listEvaluatorProfiles()
    },
    null,
    2
  );
}

export function importEvaluatorBackup(jsonText: string) {
  const parsed = JSON.parse(jsonText);
  if (parsed?.backup_type !== "arbeidsevne-veilederdata" || !Array.isArray(parsed.profiles)) {
    throw new Error("Filen er ikke en gyldig veilederbackup.");
  }
  const existing = readProfiles();
  const merged = [...existing];
  for (const profile of parsed.profiles as EvaluatorProfile[]) {
    const index = merged.findIndex((item) => item.id === profile.id);
    if (index >= 0) {
      merged[index] = {
        ...normalizeProfile(merged[index]),
        ...normalizeProfile(profile),
        display_name: normalizeProfile(merged[index]).display_name || normalizeProfile(profile).display_name
      };
    } else {
      merged.push(normalizeProfile(profile));
    }
  }
  writeProfiles(merged);
}

export function extractReports(payload: ExportPayload | StoredEntry[] | { reports?: StoredEntry[] }) {
  if (Array.isArray(payload)) return payload;
  if (payload && Array.isArray(payload.reports)) return payload.reports;
  throw new Error("Filen inneholder ikke en gjenkjennbar rapporteksport.");
}

export function reportSignature(entry: Partial<StoredEntry>) {
  if (entry.id) return `id:${entry.id}`;
  const values =
    entry.type === "work_report"
      ? [
          entry.created_at,
          entry.report_date,
          entry.report_time,
          (entry as Partial<Report>).work_ability,
          (entry as Partial<Report>).energy_level,
          (entry as Partial<Report>).status
        ]
      : [entry.created_at, entry.report_date, entry.report_time, entry.type];
  return `fallback:${values.join("|")}`;
}

function normalizeImportedEntry(entry: StoredEntry): StoredEntry {
  if (entry.type === "work_report") {
    const { physical_energy_detail, mental_energy_detail, ...rest } = entry;
    return {
      ...rest,
      task_types: rest.task_types ?? [],
      main_limitations: rest.main_limitations ?? [],
      helpful_accommodations: rest.helpful_accommodations ?? [],
      physical_energy: rest.physical_energy ?? physical_energy_detail ?? rest.energy_level,
      mental_energy: rest.mental_energy ?? mental_energy_detail ?? rest.energy_level,
      total_score_percent: rest.total_score_percent ?? calculateReportScore({ ...rest, physical_energy: rest.physical_energy ?? physical_energy_detail ?? rest.energy_level, mental_energy: rest.mental_energy ?? mental_energy_detail ?? rest.energy_level }) ?? undefined
    };
  }

  return {
    ...entry,
    parent_report_id: entry.parent_report_id ?? entry.related_report_id,
    related_report_id: entry.related_report_id ?? entry.parent_report_id,
    delayed_symptoms: entry.delayed_symptoms ?? []
  };
}

function normalizeProfile(profile: EvaluatorProfile): EvaluatorProfile {
  return {
    ...profile,
    reports: (profile.reports ?? []).map(normalizeImportedEntry).sort((a, b) => getEntryTime(b) - getEntryTime(a)),
    evaluator_notes: (profile.evaluator_notes ?? []).map((note) => ({
      ...note,
      note_type: note.note_type ?? (note.related_report_id ? "report" : note.related_followup_id ? "followup" : "person")
    }))
  };
}

function upsertNoteInProfile(
  profile: EvaluatorProfile,
  text: string,
  noteTarget: Pick<EvaluatorNote, "note_type" | "related_report_id" | "related_followup_id" | "parent_report_id">,
  now: string
): EvaluatorProfile {
  const notes = profile.evaluator_notes.filter((note) => !sameNoteTarget(note, noteTarget));
  if (!text) {
    return { ...profile, evaluator_notes: notes, updated_at: now };
  }
  const existing = profile.evaluator_notes.find((note) => sameNoteTarget(note, noteTarget));
  const note: EvaluatorNote = {
    id: existing?.id ?? crypto.randomUUID(),
    created_at: existing?.created_at ?? now,
    updated_at: now,
    text,
    note_type: noteTarget.note_type,
    related_report_id: noteTarget.related_report_id,
    related_followup_id: noteTarget.related_followup_id,
    parent_report_id: noteTarget.parent_report_id
  };
  return { ...profile, evaluator_notes: [note, ...notes], updated_at: now };
}

function sameNoteTarget(note: Pick<EvaluatorNote, "note_type" | "related_report_id" | "related_followup_id">, target: Pick<EvaluatorNote, "note_type" | "related_report_id" | "related_followup_id">) {
  return (
    (note.note_type ?? "person") === (target.note_type ?? "person") &&
    (note.related_report_id ?? "") === (target.related_report_id ?? "") &&
    (note.related_followup_id ?? "") === (target.related_followup_id ?? "")
  );
}

function makeFingerprint(reports: StoredEntry[]) {
  const base = reports
    .slice()
    .sort((a, b) => reportSignature(a).localeCompare(reportSignature(b)))
    .map(reportSignature)
    .join(";");
  let hash = 0;
  for (let index = 0; index < base.length; index += 1) {
    hash = (hash * 31 + base.charCodeAt(index)) >>> 0;
  }
  return hash.toString(16);
}

function resolveImportTarget(reports: StoredEntry[], profiles: EvaluatorProfile[], targetProfileId?: string) {
  const importedIds = new Set(reports.map((report) => report.id).filter(Boolean));
  if (importedIds.size === 0 && targetProfileId) {
    return {
      action: "matched_existing_person" as const,
      person: profiles.find((profile) => profile.id === targetProfileId),
      matchedReportIds: [] as string[]
    };
  }

  const matches = profiles
    .map((person) => {
      const personIds = new Set(person.reports.map((report) => report.id).filter(Boolean));
      const matchedReportIds = [...importedIds].filter((id) => personIds.has(id));
      return { person, matchCount: matchedReportIds.length, matchedReportIds };
    })
    .filter((match) => match.matchCount > 0)
    .sort((a, b) => b.matchCount - a.matchCount);

  if (matches.length === 0) return { action: "created_new_person" as const, person: undefined, matchedReportIds: [] as string[] };
  if (matches.length === 1) {
    return {
      action: "matched_existing_person" as const,
      person: matches[0].person,
      matchedReportIds: matches[0].matchedReportIds
    };
  }
  return {
    action: "conflict_requires_manual_resolution" as const,
    matches,
    matchedReportIds: matches.flatMap((match) => match.matchedReportIds)
  };
}
