'use client';

import { useState } from 'react';

interface ImportSummary {
  mode: 'merge' | 'replace';
  exercisesCreated: number;
  exercisesSkipped: number;
  workoutsCreated: number;
  setsCreated: number;
  setsSkipped: number;
}

export default function ExportMyData() {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [summary, setSummary] = useState<ImportSummary | null>(null);

  const handleExport = async () => {
    setError(null);
    setSummary(null);
    setBusy(true);
    try {
      const res = await fetch('/api/me/export');
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error ?? `HTTP ${res.status}`);
      }
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      const cd = res.headers.get('content-disposition');
      const match = cd?.match(/filename="([^"]+)"/);
      a.download = match?.[1] ?? 'proof-of-work-export.json';
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const handleImport = async (
    file: File,
    mode: 'merge' | 'replace',
  ) => {
    setError(null);
    setSummary(null);
    setBusy(true);
    try {
      const text = await file.text();
      let payload: unknown;
      try {
        payload = JSON.parse(text);
      } catch {
        throw new Error('Selected file is not valid JSON.');
      }
      const body: Record<string, unknown> = { payload, mode };
      if (mode === 'replace') body.confirm = 'REPLACE';
      const res = await fetch('/api/me/import', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const errBody = await res.json().catch(() => ({}));
        throw new Error(errBody.error ?? `HTTP ${res.status}`);
      }
      setSummary((await res.json()) as ImportSummary);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const onPickMerge = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (f) void handleImport(f, 'merge');
    e.target.value = '';
  };

  const onPickReplace = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (!f) return;
    if (
      !window.confirm(
        'REPLACE deletes every workout, set, exercise, and program currently in your account before importing the file. This is irreversible. Continue?',
      )
    ) {
      e.target.value = '';
      return;
    }
    void handleImport(f, 'replace');
    e.target.value = '';
  };

  return (
    <section className="bg-zinc-900 rounded border border-zinc-800 p-6 space-y-4">
      <header>
        <h2 className="text-sm font-semibold text-white uppercase tracking-wider">
          Export &amp; import my data
        </h2>
        <p className="text-xs text-zinc-500 mt-1">
          Download a JSON file with every workout, set, exercise, and
          program tied to your account. Re-import on another instance
          (or this one after a wipe) to restore.
        </p>
      </header>

      <div className="flex flex-wrap gap-2">
        <button
          type="button"
          onClick={handleExport}
          disabled={busy}
          className="text-xs px-3 py-1.5 rounded border border-zinc-700 text-white uppercase tracking-wider hover:bg-zinc-800 disabled:opacity-50"
        >
          {busy ? 'Working...' : 'Download JSON'}
        </button>

        <label className="text-xs px-3 py-1.5 rounded border border-zinc-700 text-white uppercase tracking-wider hover:bg-zinc-800 cursor-pointer">
          Import (merge)
          <input
            type="file"
            accept="application/json,.json"
            onChange={onPickMerge}
            disabled={busy}
            className="hidden"
          />
        </label>

        <label className="text-xs px-3 py-1.5 rounded border border-red-900 text-red-400 uppercase tracking-wider hover:bg-red-900/30 cursor-pointer">
          Import (replace)
          <input
            type="file"
            accept="application/json,.json"
            onChange={onPickReplace}
            disabled={busy}
            className="hidden"
          />
        </label>
      </div>

      <p className="text-xs text-zinc-500">
        <strong className="text-zinc-300">Merge</strong> keeps your existing
        data and adds the imported rows. Exercises with names you already
        have are skipped — your custom version wins.{' '}
        <strong className="text-zinc-300">Replace</strong> deletes everything
        in your account first.
      </p>

      {error && (
        <div className="rounded bg-red-900/50 px-3 py-2 border border-red-800 text-xs text-red-400">
          {error}
        </div>
      )}
      {summary && (
        <div className="rounded bg-emerald-900/40 px-3 py-2 border border-emerald-800 text-xs text-emerald-300">
          Imported in <strong>{summary.mode}</strong> mode —{' '}
          {summary.exercisesCreated} exercises created
          {summary.exercisesSkipped > 0
            ? `, ${summary.exercisesSkipped} skipped (already existed)`
            : ''}
          ; {summary.workoutsCreated} workouts created;{' '}
          {summary.setsCreated} sets imported
          {summary.setsSkipped > 0
            ? ` (${summary.setsSkipped} skipped — exercise not found)`
            : ''}
          .
        </div>
      )}
    </section>
  );
}
