import { Hono } from 'hono'
import { serveStatic } from 'hono/bun'
import { basename, join } from 'path'
import { mkdir, readdir } from 'node:fs/promises'
import { nanoid } from 'nanoid'
import KV, { type Keys } from '@workshop/shared/kv'
import { Dirent } from 'node:fs'
import { html } from 'hono/html'

declare global {
  interface Window {
    location: Location
  }
  var location: Location
}

type Project = {
  id: string
  name: string
  createdAt: string
}

declare module "@workshop/shared/kv" {
  interface Keys {
    projects: Project[]
  }
}


const app = new Hono()
const PROJECTS_DIR = './projects'

app.get('/projects', async c => {
  const projects = await loadProjects()
  return c.html(
    <Layout title="Projects">
      <Projects projects={projects} />
    </Layout>
  )
})

app.get('/project/:id', async c => {
  const id = c.req.param('id')
  const { project, files } = await loadProject(id, { files: true })
  if (!project) return c.json({ error: 'Not found' }, 404)
  return c.html(
    <Layout title={project.name}>
      <Project project={project} files={files!} />
    </Layout>
  )
})

app.get('/new', async c => {
  return c.html(
    <Layout title="New Project">
      <NewProject />
    </Layout>
  )
})

const api = new Hono()

api.get('/projects', async c => {
  const projects = await loadProjects()
  return c.json(projects)
})

api.post('/projects', async c => {
  const form = await c.req.formData()
  const name = form.get('name')
  if (!name) return c.json({ error: "Name is required" }, 400)
  if (typeof name !== 'string') return c.json({ error: "Name must be a string" }, 400)

  const projects = await loadProjects()

  if (projects.some(p => p.name === name))
    return c.json({ error: "A project with this name already exists" }, 409)

  const id = nanoid(6)
  projects.push({ id, name, createdAt: new Date().toISOString() })
  await mkdir(join(PROJECTS_DIR, `project_${id}`), { recursive: true })
  await saveProjects(projects)
  return c.json(projects[projects.length - 1])
})

api.patch('/projects/:id', async c => {
  const id = c.req.param('id')
  const { name } = await c.req.json()
  const { project } = await loadProject(id)
  if (!project) return c.json({ error: 'Not found' }, 404)
  project.name = name
  await saveProject(project)
  return c.json(project)
})

api.get('/project/:id', async c => {
  const id = c.req.param('id')
  try {
    const { project, files } = await loadProject(id, { files: true })
    return c.json({ files, project })
  } catch {
    return c.json({ error: 'Not found' }, 404)
  }
})

api.post('/project/:id/upload', async c => {
  const id = c.req.param('id')

  if (id !== basename(id))
    return c.json({ error: 'Invalid project id' }, 400)

  const folder = join(PROJECTS_DIR, `project_${id}`)
  try {
    await mkdir(folder, { recursive: true })

    const form = await c.req.formData()
    const file = form.get('file')
    if (!(file instanceof File))
      return c.json({ error: 'Invalid file' }, 400)


    // strip any directory parts from the uploaded filename
    const filename = basename(file.name)
    const filepath = join(folder, filename)
    await Bun.write(filepath, await file.arrayBuffer())

    return c.json({ status: 'ok' })
  } catch (err) {
    console.error('Upload error:', err)
    return c.json({ error: 'Upload failed' }, 500)
  }
})

api.get('/project/:id/file/:filename', async c => {
  const { id, filename } = c.req.param()
  const path = join(PROJECTS_DIR, `project_${id}`, filename)
  const file = Bun.file(path)
  if (!(await file.exists())) return c.json({ error: 'Not found' }, 404)

  return new Response(file, {
    headers: {
      'Content-Type': file.type || 'application/octet-stream',
    },
  })
})

api.delete('/project/:id/file/:filename', async c => {
  const { id, filename } = c.req.param()
  const path = join(PROJECTS_DIR, `project_${id}`, filename)
  try {
    await Bun.file(path).delete()
    return c.text('Deleted')
  } catch {
    return c.json({ error: 'Not found' }, 404)
  }
})

api.delete("/project/:id", async c => {
  const id = c.req.param("id")
  const { project } = await loadProject(id)
  if (!project) return c.json({ error: "Not found" }, 404)

  const projects = await loadProjects()
  const index = projects.findIndex(p => p.id === id)
  if (index !== -1) {
    projects.splice(index, 1)
    await saveProjects(projects)
  }
  return c.json({ status: "ok" })
})

app.route('/api', api)
app.use('/public/*', serveStatic({ root: './' }))

async function loadProject(id: string, { files }: { files?: boolean } = {}): Promise<{ project: Project | null, files?: string[] }> {
  const projects = await loadProjects()
  const project = projects.find(p => p.id === id)
  if (!project) return { project: null }

  if (files) {
    const folder = join(PROJECTS_DIR, `project_${id}`)
    const files = (await readdir(folder, { withFileTypes: true })).filter(f => f.isFile()).map(f => f.name)
    return { project, files }
  }

  return { project }
}

async function loadProjects(): Promise<Project[]> {
  return (await KV.get("projects")) ?? []
}

async function saveProject(project: Project) {
  const projects = await loadProjects()
  const index = projects.findIndex(p => p.id === project.id)
  if (index !== -1) {
    projects[index] = project
  } else {
    projects.push(project)
  }
  await saveProjects(projects)
}

async function saveProjects(projects: Project[]) {
  await KV.set("projects", projects)
}

const Projects = ({ projects }: { projects: Project[] }) => {
  return (
    <div>
      <h1 class="text-3xl font-bold mb-6">Projects</h1>
      <ul class="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3">
        {projects.map(project => (
          <li key={project.id} class="bg-white p-6 rounded-lg shadow-sm hover:shadow-md transition-shadow">
            <a href={`/project/${project.id}`} class="block">
              <h2 class="text-xl font-semibold text-gray-900">{project.name}</h2>
              <p class="text-sm text-gray-500 mt-2">
                Created {new Date(project.createdAt).toLocaleDateString()}
              </p>
            </a>
          </li>
        ))}
      </ul>
    </div>
  )
}

const Project = ({ project, files }: { project: Project, files: string[] }) => {
  return (
    <div>
      <div class="flex items-center justify-between mb-6">
        <h1 class="text-3xl font-bold">{project.name}</h1>
        <button
          class="text-red-600 hover:text-red-700 text-sm border border-red-200 hover:border-red-300 px-3 py-1 rounded transition-colors"
          data-project={project.id}
          onclick="deleteProject(event)"
        >
          Delete Project
        </button>
      </div>
      <div class="bg-white rounded-lg shadow-sm p-6">
        <h2 class="text-xl font-semibold mb-4">Files</h2>
        <div id="upload-progress" class="hidden mb-4">
          <div class="flex items-center gap-2 text-sm text-gray-600 mb-2">
            <span id="upload-filename"></span>
            <span id="upload-percent">0%</span>
          </div>
          <div class="w-full bg-gray-200 rounded-full h-2">
            <div id="upload-bar" class="bg-blue-500 h-2 rounded-full w-0 transition-all"></div>
          </div>
        </div>
        <ul class="space-y-2">
          {files.map(file => (
            <li key={file} class="flex items-center justify-between py-2 px-4 hover:bg-gray-50 rounded">
              <span class="text-gray-900">{file}</span>
              <div class="flex gap-2">
                <a
                  href={`/api/project/${project.id}/file/${file}`}
                  class="text-blue-500 hover:text-blue-600"
                  download
                >
                  Download
                </a>
                <button
                  class="text-red-500 hover:text-red-600"
                  data-file={file}
                  data-project={project.id}
                  onclick="deleteFile(event)"
                >
                  Delete
                </button>
              </div>
            </li>
          ))}
        </ul>
      </div>
      {html`
        <script>
          function deleteFile(e) {
            const button = e.target
            const file = button.dataset.file
            const project = button.dataset.project

            if (!confirm('Delete ' + file + '?')) return

            fetch('/api/project/' + project + '/file/' + file, {
              method: 'DELETE'
            }).then(() => location.reload())
          }

          function deleteProject(e) {
            const button = e.target
            const project = button.dataset.project

            if (!confirm('Delete this project and all its files?')) return

            fetch('/api/project/' + project, {
              method: 'DELETE'
            }).then(() => location.href = '/projects')
          }

          function showProgress(file) {
            const progress = document.getElementById("upload-progress")
            const filename = document.getElementById("upload-filename")
            const percent = document.getElementById("upload-percent")
            const bar = document.getElementById("upload-bar")

            progress.classList.remove("hidden")
            filename.textContent = file.name
            percent.textContent = "0%"
            bar.style.width = "0%"
          }

          function updateProgress(percent) {
            document.getElementById("upload-percent").textContent = percent + "%"
            document.getElementById("upload-bar").style.width = percent + "%"
          }

          function hideProgress() {
            document.getElementById("upload-progress").classList.add("hidden")
          }
        </script>
      `}
    </div>
  )
}

const NewProject = () => {
  return (
    <div>
      <h1 class="text-3xl font-bold mb-6">New Project</h1>
      <div class="bg-white rounded-lg shadow-sm p-6">
        <form
          class="flex gap-4 items-center"
          onsubmit="handleSubmit(event)"
        >
          <input
            type="text"
            name="name"
            placeholder="Project name"
            required
            class="flex-1 border border-gray-300 rounded-md p-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
          <button type="submit" class="bg-blue-500 text-white px-6 py-2 rounded-md hover:bg-blue-600 transition-colors">
            Create
          </button>
        </form>
      </div>
      {html`
        <script>
          function handleSubmit(e) {
            e.preventDefault()
            const form = e.target
            const formData = new FormData(form)

            fetch('/api/projects', {
              method: 'POST',
              body: formData
            })
              .then(res => res.json())
              .then(() => location.href = '/projects')
          }
        </script>
      `}
    </div>
  )
}

const Layout = ({ children, title }: { children: any, title: string }) => {
  return (
    <html>
      <head>
        <title>{title} - 💼 Attaché</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link rel="icon" type="image/png" href="/public/favicon.png" />
        <style>{`
          .drag-active {
            position: relative;
          }
          .drag-active::after {
            content: "Drop files to upload";
            position: fixed;
            inset: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            background: rgba(59, 130, 246, 0.1);
            backdrop-filter: blur(2px);
            z-index: 50;
          }
        `}</style>
      </head>
      <body
        class="min-h-screen bg-gray-50"
        ondragover="handleGlobalDragOver(event)"
        ondragleave="handleGlobalDragLeave(event)"
        ondrop="handleGlobalDrop(event)"
      >
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <nav class="mb-8">
            <div class="flex items-center justify-between">
              <a href="/projects" class="text-2xl font-bold text-gray-900">💼 Attaché</a>
              <a href="/new" class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition-colors">
                New Project
              </a>
            </div>
          </nav>
          <main>{children}</main>
        </div>
        {html`
          <script>
            function handleGlobalDragOver(e) {
              e.preventDefault()
              e.stopPropagation()

              if (window.location.pathname.startsWith("/project/")) {
                document.body.classList.add("drag-active")
              }
            }

            function handleGlobalDragLeave(e) {
              e.preventDefault()
              e.stopPropagation()

              const rect = document.body.getBoundingClientRect()
              if (
                e.clientX <= rect.left ||
                e.clientX >= rect.right ||
                e.clientY <= rect.top ||
                e.clientY >= rect.bottom
              ) {
                document.body.classList.remove("drag-active")
              }
            }

            function handleGlobalDrop(e) {
              e.preventDefault()
              e.stopPropagation()

              document.body.classList.remove("drag-active")

              if (!window.location.pathname.startsWith("/project/")) {
                return
              }

              const files = e.dataTransfer.files
              const projectId = document.querySelector("[data-project]").dataset.project

              let currentUpload = Promise.resolve()

              for (const file of files) {
                currentUpload = currentUpload.then(async () => {
                  const formData = new FormData()
                  formData.append("file", file)

                  showProgress(file)

                  try {
                    const xhr = new XMLHttpRequest()
                    await new Promise((resolve, reject) => {
                      xhr.upload.onprogress = (e) => {
                        if (e.lengthComputable) {
                          const percent = Math.round((e.loaded / e.total) * 100)
                          updateProgress(percent)
                        }
                      }

                      xhr.onload = () => {
                        if (xhr.status === 200) {
                          resolve()
                        } else {
                          reject(new Error("Upload failed"))
                        }
                      }

                      xhr.onerror = () => reject(new Error("Upload failed"))

                      xhr.open("POST", "/api/project/" + projectId + "/upload")
                      xhr.send(formData)
                    })
                  } catch (err) {
                    console.error("Upload failed:", err)
                  } finally {
                    hideProgress()
                  }
                })
              }

              currentUpload.then(() => location.reload())
            }
          </script>
        `}
      </body>
    </html>
  )
}

export default {
  port: 3000,
  fetch: app.fetch,
  maxRequestBodySize: 1024 * 1024 * 1024, // 1GB
}