"use client";
import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import Editor from "@monaco-editor/react";
import { useEditor } from "@/hooks/useEditor";

const TEXT_EXT = ["js","ts","tsx","jsx","json","md","css","html","txt","mjs","cjs","tsconfig","eslintrc","prettierrc"];
function isTextFile(path: string) {
  const ext = (path.split('.').pop() || '').toLowerCase();
  return TEXT_EXT.includes(ext) || path.endsWith('.d.ts');
}

export function FilesExplorerButton() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <Button size="xs" variant="outline" className="!rounded-md" onClick={() => setOpen(true)}>Files</Button>
      {open && <FilesExplorer open={open} onClose={() => setOpen(false)} />}
    </>
  );
}

function FilesExplorer({ open, onClose }: { open: boolean; onClose: () => void }) {
  const { project } = useEditor();
  const space = project?.space_id || '';
  const [namespace, repoId] = space.split('/');
  const [paths, setPaths] = useState<{ path: string; type: string }[]>([]);
  const [selected, setSelected] = useState<string | null>(null);
  const [content, setContent] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  const canSave = useMemo(() => !!selected && isTextFile(selected!), [selected]);

  useEffect(() => {
    (async () => {
      if (!namespace || !repoId) return;
      const res = await fetch(`/api/me/projects/${namespace}/${repoId}/files`);
      const data = await res.json();
      if (data?.ok) setPaths(data.paths || []);
    })();
  }, [namespace, repoId]);

  const openFile = async (p: string) => {
    setSelected(p);
    setContent('');
    setLoading(true);
    try {
      if (isTextFile(p)) {
        const res = await fetch(`/api/me/projects/${namespace}/${repoId}/file?path=${encodeURIComponent(p)}`);
        const data = await res.json();
        if (data?.ok) setContent(data.content || '');
      }
    } finally {
      setLoading(false);
    }
  };

  const saveFile = async () => {
    if (!selected) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/me/projects/${namespace}/${repoId}/apply`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ files: [{ path: selected, action: 'update', content }], commitTitle: `Edit ${selected}` })
      });
      await res.json();
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={() => onClose()}>
      <DialogContent className="sm:max-w-5xl !bg-neutral-900 !border-neutral-800">
        <DialogHeader>
          <DialogTitle className="text-neutral-100">Project Files</DialogTitle>
        </DialogHeader>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3 min-h-[420px]">
          <div className="border border-neutral-800 rounded-lg p-2 overflow-y-auto">
            <ul className="text-sm text-neutral-300">
              {paths.map(p => (
                <li key={p.path} className="py-1 px-2 rounded hover:bg-neutral-800 cursor-pointer" onClick={() => openFile(p.path)}>
                  {p.path}
                </li>
              ))}
            </ul>
          </div>
          <div className="md:col-span-2 border border-neutral-800 rounded-lg overflow-hidden relative">
            {!selected && <div className="p-4 text-neutral-400 text-sm">Select a file to preview/edit</div>}
            {selected && isTextFile(selected) && (
              <Editor
                defaultLanguage="plaintext"
                theme="vs-dark"
                value={content}
                loading={<div className="p-4 text-neutral-400 text-sm">{loading ? 'Loading…' : ''}</div>}
                onChange={(v) => setContent(v || '')}
                options={{ minimap: { enabled: false }, wordWrap: 'on' }}
              />
            )}
            {selected && !isTextFile(selected) && (
              <div className="p-4 text-neutral-400 text-sm">Binary/non-text file. Download/edit locally if needed.</div>
            )}
          </div>
        </div>
        <DialogFooter>
          <Button variant="bordered" size="sm" onClick={() => onClose()}>Close</Button>
          <Button size="sm" onClick={saveFile} disabled={!canSave || saving}>{saving ? 'Saving…' : 'Save File'}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

