"use client";
import { useState } from 'react';

type Props = {
  id: number;
  title: string;
  description: string;
  transcript: string;
  analysis: { ingredients: any[]; prep_steps: string[]; cooking_steps: string[] };
  folders: Array<{ id: number; name: string }>;
  folderId: number | null;
};

export default function Editor({ id, title, description, transcript, analysis, folders, folderId }: Props) {
  const [isEditing, setIsEditing] = useState(false);
  const [t, setT] = useState(title || '');
  const [desc, setDesc] = useState(description || '');
  const [trans, setTrans] = useState(transcript || '');
  const [ingText, setIngText] = useState((analysis?.ingredients || []).map((i: any) => `${i.quantity ?? ''} ${i.unit ?? ''} ${i.name}`.trim()).join('\n'));
  const [prepText, setPrepText] = useState((analysis?.prep_steps || []).join('\n'));
  const [cookText, setCookText] = useState((analysis?.cooking_steps || []).join('\n'));
  const [folder, setFolder] = useState<number | null>(folderId ?? null);
  const [saving, setSaving] = useState(false);

  async function save() {
    setSaving(true);
    try {
      const newAnalysis = {
        ingredients: ingText.split(/\r?\n/).map((l) => ({ name: l.trim(), quantity: null, unit: null })).filter((x) => x.name),
        prep_steps: prepText.split(/\r?\n/).map((s) => s.trim()).filter(Boolean),
        cooking_steps: cookText.split(/\r?\n/).map((s) => s.trim()).filter(Boolean),
      };
      const res = await fetch(`/api/recipes/${id}`, {
        method: 'PATCH',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ title: t, description: desc, transcript: trans, analysis: newAnalysis, folderId: folder }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || 'Failed to save');
      alert('Saved');
    } catch (e: any) {
      alert(e?.message || 'Failed to save');
    } finally {
      setSaving(false);
    }
  }

  if (!isEditing) {
    return (
      <div className="space-y-6">
        {desc && (
          <div className="whitespace-pre-wrap text-neutral-700 dark:text-neutral-300"><span className="font-medium">Description:</span> {desc}</div>
        )}

        <div>
          <h2 className="text-xl font-semibold">Ingredients</h2>
          <ul className="list-disc pl-6 mt-2 space-y-1">
            {(analysis?.ingredients || []).map((it: any, idx: number) => (
              <li key={idx}>
                <span className="font-medium">{it.name}</span>
                {it.quantity ? ` – ${it.quantity}` : ''}
                {it.unit ? ` ${it.unit}` : ''}
                {it.notes ? ` (${it.notes})` : ''}
              </li>
            ))}
          </ul>
        </div>

        {/* Prep section with numbering 1.x */}
        <div>
          <h2 className="text-xl font-semibold">Prep</h2>
          <ol className="pl-6 mt-2 space-y-3">
            {((analysis as any)?.detailed?.prep || (analysis?.prep_steps || [])).map((s: any, i: number) => (
              <li key={i} className="marker:hidden">
                <div className="text-amber-600 font-semibold">{`1.${i + 1}`}</div>
                {typeof s === 'string' ? (
                  <p className="mt-1">{s}</p>
                ) : (
                  <div className="mt-1">
                    <div className="font-medium">{s.title}</div>
                    <p>{s.body}</p>
                  </div>
                )}
              </li>
            ))}
          </ol>
        </div>

        {/* Cook section with numbering 2.x */}
        <div>
          <h2 className="text-xl font-semibold">Cook</h2>
          <ol className="pl-6 mt-2 space-y-3">
            {((analysis as any)?.detailed?.cook || (analysis?.cooking_steps || [])).map((s: any, i: number) => (
              <li key={i} className="marker:hidden">
                <div className="text-amber-600 font-semibold">{`2.${i + 1}`}</div>
                {typeof s === 'string' ? (
                  <p className="mt-1">{s}</p>
                ) : (
                  <div className="mt-1">
                    <div className="font-medium">{s.title}</div>
                    <p>{s.body}</p>
                  </div>
                )}
              </li>
            ))}
          </ol>
        </div>

        {trans && (
          <details className="mt-4">
            <summary className="cursor-pointer font-medium">Transcript</summary>
            <pre className="whitespace-pre-wrap text-sm mt-2">{trans}</pre>
          </details>
        )}

        <div className="pt-2">
          <button onClick={() => setIsEditing(true)} className="inline-flex items-center justify-center rounded border border-neutral-300 dark:border-neutral-700 px-4 py-2">Edit</button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <label className="block text-sm font-medium">Title</label>
        <input className="w-full rounded border border-neutral-300 dark:border-neutral-700 bg-transparent px-3 py-2" value={t} onChange={(e) => setT(e.target.value)} />
      </div>
      <div>
        <label className="block text-sm font-medium">Folder</label>
        <select className="w-full rounded border border-neutral-300 dark:border-neutral-700 bg-transparent px-3 py-2" value={folder ?? ''} onChange={(e) => setFolder(e.target.value ? Number(e.target.value) : null)}>
          <option value="">Unsorted</option>
          {folders.map((f) => (
            <option key={f.id} value={f.id}>{f.name}</option>
          ))}
        </select>
      </div>
      <div>
        <label className="block text-sm font-medium">Description</label>
        <textarea className="w-full rounded border border-neutral-300 dark:border-neutral-700 bg-transparent px-3 py-2" rows={3} value={desc} onChange={(e) => setDesc(e.target.value)} />
      </div>
      <div>
        <label className="block text-sm font-medium">Ingredients (one per line)</label>
        <textarea className="w-full rounded border border-neutral-300 dark:border-neutral-700 bg-transparent px-3 py-2" rows={6} value={ingText} onChange={(e) => setIngText(e.target.value)} />
      </div>
      <div>
        <label className="block text-sm font-medium">Prep Steps (one per line)</label>
        <textarea className="w-full rounded border border-neutral-300 dark:border-neutral-700 bg-transparent px-3 py-2" rows={6} value={prepText} onChange={(e) => setPrepText(e.target.value)} />
      </div>
      <div>
        <label className="block text-sm font-medium">Cooking Steps (one per line)</label>
        <textarea className="w-full rounded border border-neutral-300 dark:border-neutral-700 bg-transparent px-3 py-2" rows={6} value={cookText} onChange={(e) => setCookText(e.target.value)} />
      </div>
      <div>
        <label className="block text-sm font-medium">Transcript</label>
        <textarea className="w-full rounded border border-neutral-300 dark:border-neutral-700 bg-transparent px-3 py-2" rows={6} value={trans} onChange={(e) => setTrans(e.target.value)} />
      </div>
      <div className="flex gap-2">
        <button onClick={save} disabled={saving} className="inline-flex items-center justify-center rounded bg-black text-white dark:bg.white dark:text-black px-4 py-2 disabled:opacity-60">{saving ? 'Saving…' : 'Save Changes'}</button>
        <button onClick={() => setIsEditing(false)} className="inline-flex items-center justify-center rounded border border-neutral-300 dark:border-neutral-700 px-4 py-2">Cancel</button>
      </div>
    </div>
  );
}


