'use client'

import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Download, Lock, LockOpen, Upload } from 'lucide-react'
import { toast } from 'sonner'
import { api, type DocumentRecord, type PaginatedResponse } from '@/lib/api'
import { DataTable } from '@/components/DataTable'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Badge } from '@/components/ui/Badge'
import { PermissionGate } from '@/components/auth/PermissionGate'

async function fileToBase64(file: File): Promise<string> {
  const buf = await file.arrayBuffer()
  let binary = ''
  const bytes = new Uint8Array(buf)
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i])
  return btoa(binary)
}

export function DocumentsPage() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [search, setSearch] = useState('')
  const [page, setPage] = useState(1)
  const [title, setTitle] = useState('')
  const [folderPath, setFolderPath] = useState('/')
  const [file, setFile] = useState<File | null>(null)

  const { data, isLoading } = useQuery({
    queryKey: ['documents', search, page],
    queryFn: () =>
      api.get<PaginatedResponse<DocumentRecord>>(
        search ? '/documents/search' : '/documents',
        {
          params: search
            ? { q: search, page, per_page: 25 }
            : { search: undefined, page, per_page: 25 },
        },
      ),
  })

  const upload = useMutation({
    mutationFn: async () => {
      const content_base64 = file ? await fileToBase64(file) : undefined
      return api.post('/documents', {
        title: title || file?.name || 'Document',
        file_name: file?.name || `${title || 'document'}.txt`,
        folder_path: folderPath || '/',
        mime_type: file?.type || 'application/octet-stream',
        content_base64,
      })
    },
    onSuccess: () => {
      toast.success(t('documents.messages.uploaded'))
      setTitle('')
      setFile(null)
      queryClient.invalidateQueries({ queryKey: ['documents'] })
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const lockMut = useMutation({
    mutationFn: ({ id, lock }: { id: number; lock: boolean }) =>
      api.post(`/documents/${id}/${lock ? 'lock' : 'unlock'}`),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['documents'] }),
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const download = (id: number, fileName: string) => {
    api
      .get(`/documents/${id}/download`, { responseType: 'blob' })
      .then((res) => {
        const url = URL.createObjectURL(res.data)
        const a = document.createElement('a')
        a.href = url
        a.download = fileName || `document-${id}`
        a.click()
        URL.revokeObjectURL(url)
      })
      .catch(() => toast.error(t('common.somethingWentWrong')))
  }

  const rows = data?.data.data ?? []
  const meta = data?.data.meta

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex flex-wrap items-center justify-between gap-3">
        <h1 className="premium-heading text-2xl font-bold">{t('documents.title')}</h1>
      </div>

      <PermissionGate permission="documents.manage">
        <div className="animate-fade-in-up stagger-1 premium-card space-y-3 rounded-2xl p-5">
          <h2 className="text-sm font-semibold">{t('documents.upload')}</h2>
          <div className="grid gap-3 md:grid-cols-3">
            <Input
              label={t('documents.form.title')}
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
            <Input
              label={t('documents.form.folder')}
              value={folderPath}
              onChange={(e) => setFolderPath(e.target.value)}
            />
            <div>
              <label className="mb-1 block text-xs font-semibold text-[var(--premium-muted-text)]">
                {t('documents.form.file')}
              </label>
              <input
                type="file"
                onChange={(e) => setFile(e.target.files?.[0] ?? null)}
                className="block w-full text-sm"
              />
            </div>
          </div>
          <Button
            size="sm"
            onClick={() => upload.mutate()}
            disabled={upload.isPending || (!title && !file)}
          >
            <Upload size={14} />
            {t('documents.upload')}
          </Button>
        </div>
      </PermissionGate>

      <DataTable
        data={rows}
        loading={isLoading}
        emptyMessage={t('common.noResults')}
        onSearch={(q) => {
          setSearch(q)
          setPage(1)
        }}
        searchValue={search}
        searchPlaceholder={t('documents.search')}
        pagination={meta}
        onPageChange={setPage}
        columns={[
          { key: 'title', header: t('documents.form.title') },
          { key: 'file_name', header: t('documents.form.fileName'), className: 'font-mono text-xs' },
          { key: 'folder_path', header: t('documents.form.folder') },
          {
            key: 'version',
            header: t('documents.version'),
            render: (r) => `v${r.version}`,
          },
          {
            key: 'lock_status',
            header: t('documents.lock'),
            render: (r) => (
              <Badge variant={r.lock_status === 'locked' ? 'danger' : 'success'}>
                {t(`documents.lockStatus.${r.lock_status}`, r.lock_status)}
              </Badge>
            ),
          },
          {
            key: 'actions',
            header: t('common.actions'),
            render: (r) => (
              <div className="flex flex-wrap gap-1">
                <Button size="sm" variant="ghost" onClick={() => download(r.id, r.file_name)}>
                  <Download size={14} />
                </Button>
                <PermissionGate permission="documents.manage">
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={() =>
                      lockMut.mutate({ id: r.id, lock: r.lock_status !== 'locked' })
                    }
                  >
                    {r.lock_status === 'locked' ? <LockOpen size={14} /> : <Lock size={14} />}
                  </Button>
                </PermissionGate>
              </div>
            ),
          },
        ]}
      />
    </div>
  )
}
