'use client'

import { useState } from 'react'
import { PrimaryButton, TextField } from '@/app/FormFields'
import { useI18n } from '@/lib/i18n/client'

type Project = {
  id: string
  name: string
  isActive: boolean
  createdAt: string
  createdByName: string | null
  createdByEmail: string | null
}

export default function ProjectsClient({ initialProjects }: { initialProjects: Project[] }) {
  const { t } = useI18n()
  const [projects, setProjects] = useState<Project[]>(initialProjects)
  const [newName, setNewName] = useState('')
  const [adding, setAdding] = useState(false)
  const [addError, setAddError] = useState<string | null>(null)

  async function handleAdd(e: React.FormEvent) {
    e.preventDefault()
    if (!newName.trim()) return
    setAdding(true)
    setAddError(null)

    const res = await fetch('/api/admin/projects', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: newName }),
    })

    if (!res.ok) {
      const data = await res.json().catch(() => ({}))
      setAddError(data.error ?? t('projects.addError'))
      setAdding(false)
      return
    }

    const project = await res.json()
    setProjects((prev) => [...prev, project].sort((a, b) => a.name.localeCompare(b.name)))
    setNewName('')
    setAdding(false)
  }

  async function handleDeactivate(id: string) {
    const res = await fetch(`/api/admin/projects/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ isActive: false }),
    })

    if (res.ok) {
      setProjects((prev) => prev.filter((p) => p.id !== id))
    }
  }

  function formatDate(iso: string) {
    return new Intl.DateTimeFormat('en', { month: 'short', day: 'numeric', year: 'numeric' }).format(new Date(iso))
  }

  return (
    <div className="space-y-6">
      <form onSubmit={handleAdd} className="flex gap-2">
        <TextField
          type="text"
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
          placeholder={t('projects.projectNamePlaceholder')}
          className="flex-1"
        />
        <PrimaryButton
          type="submit"
          disabled={adding || !newName.trim()}
        >
          {adding ? t('projects.adding') : t('projects.addProject')}
        </PrimaryButton>
      </form>
      {addError && <p className="text-sm text-red-700 dark:text-red-300">{addError}</p>}

      <div className="overflow-hidden rounded-lg border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-900">
        {projects.length === 0 ? (
          <p className="px-6 py-12 text-center text-sm text-zinc-600 dark:text-zinc-400">
            {t('projects.noProjects')}
          </p>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-zinc-200 bg-zinc-50 text-left dark:border-zinc-800 dark:bg-zinc-800/50">
                <th className="px-4 py-3 font-medium text-zinc-700 dark:text-zinc-300">Name</th>
                <th className="px-4 py-3 font-medium text-zinc-700 dark:text-zinc-300">Created</th>
                <th className="px-4 py-3 font-medium text-zinc-700 dark:text-zinc-300">{t('projects.createdBy')}</th>
                <th className="px-4 py-3" />
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
              {projects.map((project) => (
                <tr key={project.id} className="hover:bg-zinc-50 dark:hover:bg-zinc-800/50">
                  <td className="px-4 py-3 font-medium text-zinc-950 dark:text-zinc-50">{project.name}</td>
                  <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">{formatDate(project.createdAt)}</td>
                  <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                    {project.createdByName ?? project.createdByEmail ?? '—'}
                  </td>
                  <td className="px-4 py-3 text-right">
                    <button
                      onClick={() => handleDeactivate(project.id)}
                      className="text-xs text-red-600 hover:underline dark:text-red-400"
                    >
                      {t('projects.deactivate')}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}
