"use client";

import { useReducer, useRef } from "react";
import Link from "next/link";
import { parseOrderCSV } from "@/lib/csv-parsers";
import { importOrdersBatch } from "@/actions/import-orders";

type PreviewRow = {
  customer_name: string;
  customer_email: string;
  customer_phone: string;
  stop_id: string;
  items: Array<{ product_id: string; quantity: number; fulfillment: string }>;
  _rowIndex: number;
};

type ImportResult = {
  imported: number;
  errors: { row: number; error: string }[];
};

type State = {
  csvText: string;
  preview: PreviewRow[] | null;
  parseErrors: { row: number; error: string }[];
  importing: boolean;
  result: ImportResult | null;
  brandId: string;
};

type Action =
  | { type: "SET_CSV_TEXT"; value: string }
  | { type: "SET_BRAND_ID"; value: string }
  | { type: "PARSE_SUCCESS"; rows: PreviewRow[]; errors: { row: number; error: string }[] }
  | { type: "PARSE_FAIL"; error: string }
  | { type: "START_IMPORT" }
  | { type: "IMPORT_SUCCESS"; result: ImportResult }
  | { type: "IMPORT_FAIL"; error: string };

const initialState: State = {
  csvText: "",
  preview: null,
  parseErrors: [],
  importing: false,
  result: null,
  brandId: "",
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_CSV_TEXT":
      return { ...state, csvText: action.value };
    case "SET_BRAND_ID":
      return { ...state, brandId: action.value };
    case "PARSE_SUCCESS":
      return { ...state, preview: action.rows, parseErrors: action.errors };
    case "PARSE_FAIL":
      return { ...state, preview: null, parseErrors: [{ row: 0, error: action.error }] };
    case "START_IMPORT":
      return { ...state, importing: true };
    case "IMPORT_SUCCESS":
      return { ...state, importing: false, result: action.result };
    case "IMPORT_FAIL":
      return {
        ...state,
        importing: false,
        result: { imported: 0, errors: [{ row: 0, error: action.error }] },
      };
  }
}

export default function SalesImportPage() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const fileRef = useRef<HTMLInputElement>(null);

  const SAMPLE_CSV = `customer_name,customer_email,customer_phone,stop_id,product_id,quantity,fulfillment
Jane Smith,jane@example.com,555-1234,{STOP_ID},{PRODUCT_ID},2,pickup
John Doe,john@example.com,555-5678,{STOP_ID},{PRODUCT_ID},1,shipping
`;

  function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      const text = ev.target?.result as string;
      dispatch({ type: "SET_CSV_TEXT", value: text });
      handlePreview(text);
    };
    reader.readAsText(file);
  }

  async function handlePreview(text?: string) {
    const toParse = text ?? state.csvText;
    if (!toParse.trim()) return;

    const parseResult = await parseOrderCSV(toParse);
    if (!parseResult.success) {
      dispatch({ type: "PARSE_FAIL", error: parseResult.error });
      return;
    }

    dispatch({ type: "PARSE_SUCCESS", rows: parseResult.rows, errors: parseResult.errors });
  }

  async function handleImport() {
    if (!state.preview || !state.brandId) return;
    dispatch({ type: "START_IMPORT" });
    const importResult = await importOrdersBatch(
      state.brandId,
      state.preview.map((r) => ({
        customer_name: r.customer_name,
        customer_email: r.customer_email,
        customer_phone: r.customer_phone,
        stop_id: r.stop_id,
        items: r.items,
      }))
    );
    if (importResult.success) {
      dispatch({
        type: "IMPORT_SUCCESS",
        result: { imported: importResult.imported, errors: importResult.errors },
      });
    } else {
      dispatch({ type: "IMPORT_FAIL", error: importResult.error });
    }
  }

  return (
    <main className="min-h-screen px-6 py-10" style={{ backgroundColor: "var(--admin-bg)" }}>
      <div className="mx-auto max-w-4xl">
        <div className="mb-6">
          <Link href="/admin/orders" className="text-sm text-stone-500 hover:text-stone-800">
            ← Back to Orders
          </Link>
          <h1 className="mt-2 text-3xl font-bold text-stone-950">Import Orders</h1>
          <p className="mt-1 text-stone-600">
            Upload a CSV to import orders from another platform. Uses existing stop and product IDs.
          </p>
        </div>

        <div className="mb-4">
          <label htmlFor="import-orders-brand" className="block text-sm font-medium text-stone-600">Brand ID</label>
          <input aria-label="64294306 5f42 463d A5e8 2ad6c81a96de"
            id="import-orders-brand"
            type="text"
            value={state.brandId}
            onChange={(e) => dispatch({ type: "SET_BRAND_ID", value: e.target.value })}
            placeholder="64294306-5f42-463d-a5e8-2ad6c81a96de"
            className="mt-1 w-full rounded-xl border border-stone-300 px-4 py-3 text-sm outline-none focus:border-blue-500 bg-white"
          />
        </div>

        <div className="mb-4 card p-6">
          <label htmlFor="import-orders-csv" className="block text-sm font-medium text-stone-600 mb-2">Upload CSV</label>
          <input aria-label="Import Orders Csv" id="import-orders-csv" ref={fileRef} type="file" accept=".csv" onChange={handleFile} className="w-full text-sm text-stone-500" />
          <p className="mt-2 text-xs text-stone-500">Paste CSV content below:</p>
          <label htmlFor="import-orders-text" className="sr-only">CSV text</label>
          <textarea aria-label="Import Orders Text"
            id="import-orders-text"
            value={state.csvText}
            onChange={(e) => dispatch({ type: "SET_CSV_TEXT", value: e.target.value })}
            rows={6}
            className="mt-2 w-full rounded-xl border border-stone-300 px-4 py-3 text-sm font-mono outline-none focus:border-blue-500 bg-white"
          />
          <button type="button"
            onClick={() => handlePreview()}
            className="mt-3 rounded-xl border border-stone-300 px-4 py-2 text-sm font-medium text-stone-700 hover:bg-stone-100"
          >
            Preview
          </button>
        </div>

        {state.parseErrors.length > 0 && (
          <div className="mb-4 rounded-xl bg-red-50 p-4 border border-red-200">
            <p className="text-sm font-semibold text-red-600">Parse Errors</p>
            <ul className="mt-1 space-y-1">
              {state.parseErrors.map((e) => (
                <li key={e.row} className="text-sm text-red-600">Row {e.row}: {e.error}</li>
              ))}
            </ul>
          </div>
        )}

        {state.preview !== null && (
          <div className="mb-4 card p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-stone-950">Preview ({state.preview.length} rows)</h2>
              <button type="button"
                onClick={handleImport}
                disabled={!state.brandId || state.importing}
                className="rounded-xl bg-blue-600 px-6 py-3 text-sm font-bold text-white disabled:opacity-50 hover:bg-blue-700"
              >
                {state.importing ? "Importing..." : `Import ${state.preview.length} Orders`}
              </button>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-stone-200">
                    <th className="text-left py-2 px-3 text-stone-500 font-medium">Customer</th>
                    <th className="text-left py-2 px-3 text-stone-500 font-medium">Email</th>
                    <th className="text-left py-2 px-3 text-stone-500 font-medium">Stop ID</th>
                    <th className="text-left py-2 px-3 text-stone-500 font-medium">Items</th>
                  </tr>
                </thead>
                <tbody>
                  {state.preview.map((row) => (
                    <tr key={row._rowIndex} className="border-b border-stone-200">
                      <td className="py-2 px-3 font-medium text-stone-950">{row.customer_name}</td>
                      <td className="py-2 px-3 text-stone-600">{row.customer_email}</td>
                      <td className="py-2 px-3 font-mono text-xs text-stone-500">{row.stop_id}</td>
                      <td className="py-2 px-3 text-stone-600">
                        {row.items.map((it) => `${it.quantity}× ${it.product_id.slice(0, 8)}`).join(", ")}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {state.result !== null && (
          <div className="card p-6">
            <h2 className="text-lg font-semibold text-stone-950">Import Result</h2>
            <div className="mt-3">
              <p className="text-3xl font-bold text-emerald-600">{state.result.imported}</p>
              <p className="text-sm text-stone-500">Orders imported</p>
            </div>
            {state.result.errors.length > 0 && (
              <ul className="mt-3 space-y-1">
                {state.result.errors.map((e, i) => (
                  <li key={`row-${e.row}-${i}`} className="text-sm text-red-600">Row {e.row}: {e.error}</li>
                ))}
              </ul>
            )}
          </div>
        )}
      </div>
    </main>
  );
}