"use client";

import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { isSpreadsheetFile } from "~/lib/excel.js";
import { parseScopeImport } from "~/lib/scopeImportParser.js";

const INPUT_CLS =
  "w-full rounded-xl border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 outline-none transition focus:border-brand-500 focus:ring-2 focus:ring-brand-100";
const LABEL_CLS = "mb-1.5 block text-xs font-semibold uppercase tracking-wide text-gray-500";

export interface EditableScopeItem {
  id?: string;
  sequenceNo: string;
  scopeType: string;
  packageCode: string;
  name: string;
  description: string;
}

export function makeScopeItem(sequenceNo: number): EditableScopeItem {
  return {
    sequenceNo: String(sequenceNo),
    scopeType: "SHOT",
    packageCode: "",
    name: "",
    description: "",
  };
}

export interface ScopeItemEditorProps {
  scopeItems: EditableScopeItem[];
  onChange: (updater: (current: EditableScopeItem[]) => EditableScopeItem[]) => void;
  scopeImportWarnings: string[];
  onScopeImportWarnings: (warnings: string[]) => void;
}

export function ScopeItemEditor({
  scopeItems,
  onChange,
  scopeImportWarnings,
  onScopeImportWarnings,
}: ScopeItemEditorProps) {
  async function handleScopeImport(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file || !isSpreadsheetFile(file)) return;
    event.target.value = "";

    try {
      const result = await parseScopeImport(file);
      onScopeImportWarnings(result.warnings);
      if (result.rows.length > 0) {
        const imported: EditableScopeItem[] = result.rows.map((row) => ({
          sequenceNo: String(row.sequenceNo),
          scopeType: row.scopeType,
          packageCode: row.packageCode,
          name: row.name,
          description: row.description,
        }));
        onChange((current) => [...current, ...imported]);
      }
    } catch {
      onScopeImportWarnings(["Failed to parse the uploaded file."]);
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-3">
        <label className="cursor-pointer rounded-2xl border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 transition hover:bg-gray-50">
          Import scope from spreadsheet
          <input type="file" accept=".xlsx,.csv" className="hidden" onChange={(event) => void handleScopeImport(event)} />
        </label>
        {scopeImportWarnings.length > 0 && (
          <div className="text-xs text-amber-700">
            {scopeImportWarnings.map((warning, index) => (
              <p key={index}>{warning}</p>
            ))}
          </div>
        )}
      </div>
      {scopeItems.map((item, index) => (
        <div key={item.id ?? `scope-${index}`} className="rounded-3xl border border-gray-200 bg-white p-5 shadow-sm">
          <div className="grid gap-4 md:grid-cols-3">
            <label>
              <span className={LABEL_CLS}>Sequence <InfoTooltip content="Ordering number for this scope item within the estimate." /></span>
              <input className={INPUT_CLS} value={item.sequenceNo} onChange={(event) => onChange((current) => current.map((entry, entryIndex) => entryIndex === index ? { ...entry, sequenceNo: event.target.value } : entry))} />
            </label>
            <label>
              <span className={LABEL_CLS}>Scope type <InfoTooltip content="Category of deliverable, e.g. SHOT, SEQUENCE, ASSET, or a custom type." /></span>
              <input className={INPUT_CLS} value={item.scopeType} onChange={(event) => onChange((current) => current.map((entry, entryIndex) => entryIndex === index ? { ...entry, scopeType: event.target.value } : entry))} />
            </label>
            <label>
              <span className={LABEL_CLS}>Package code <InfoTooltip content="Optional reference code for tracking this scope item in external systems." /></span>
              <input className={INPUT_CLS} value={item.packageCode} onChange={(event) => onChange((current) => current.map((entry, entryIndex) => entryIndex === index ? { ...entry, packageCode: event.target.value } : entry))} />
            </label>
          </div>
          <div className="mt-4 grid gap-4 lg:grid-cols-[minmax(0,0.9fr),minmax(0,1.1fr)]">
            <label>
              <span className={LABEL_CLS}>Name <InfoTooltip content="Short descriptive name for this deliverable or work package." /></span>
              <input className={INPUT_CLS} value={item.name} onChange={(event) => onChange((current) => current.map((entry, entryIndex) => entryIndex === index ? { ...entry, name: event.target.value } : entry))} />
            </label>
            <label>
              <span className={LABEL_CLS}>Description <InfoTooltip content="Detailed description of what this scope item includes." /></span>
              <textarea className={`${INPUT_CLS} min-h-24`} value={item.description} onChange={(event) => onChange((current) => current.map((entry, entryIndex) => entryIndex === index ? { ...entry, description: event.target.value } : entry))} />
            </label>
          </div>
          <div className="mt-4 flex justify-end">
            <button type="button" className="text-sm font-medium text-rose-600" onClick={() => onChange((current) => current.filter((_, entryIndex) => entryIndex !== index))}>
              Remove scope item
            </button>
          </div>
        </div>
      ))}

      <button type="button" className="rounded-2xl border border-dashed border-gray-300 px-4 py-3 text-sm font-medium text-gray-600" onClick={() => onChange((current) => [...current, makeScopeItem(current.length + 1)])}>
        Add scope item
      </button>
    </div>
  );
}
