'use client'

import { FormEvent, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Send, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import { api, type NoteItem } from '@/lib/api'
import { Button } from '@/components/ui/Button'
import { PermissionGate } from '@/components/auth/PermissionGate'

type Props = {
  entityType: string
  entityId: number | string
}

export function NotesTimeline({ entityType, entityId }: Props) {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [body, setBody] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['notes', entityType, entityId],
    queryFn: () =>
      api.get<{ data: NoteItem[] }>('/notes', {
        params: { entity_type: entityType, entity_id: entityId },
      }),
    enabled: Boolean(entityType && entityId),
  })

  const create = useMutation({
    mutationFn: () =>
      api.post('/notes', {
        entity_type: entityType,
        entity_id: Number(entityId),
        body,
      }),
    onSuccess: () => {
      setBody('')
      queryClient.invalidateQueries({ queryKey: ['notes', entityType, entityId] })
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const remove = useMutation({
    mutationFn: (id: number) => api.delete(`/notes/${id}`),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['notes', entityType, entityId] }),
  })

  const notes = data?.data.data ?? []

  const onSubmit = (e: FormEvent) => {
    e.preventDefault()
    if (!body.trim()) return
    create.mutate()
  }

  return (
    <PermissionGate permission="notes.manage">
      <div className="premium-card rounded-2xl p-5">
        <h2 className="mb-3 text-sm font-semibold">{t('notes.title')}</h2>

        <form onSubmit={onSubmit} className="mb-4 flex gap-2">
          <textarea
            value={body}
            onChange={(e) => setBody(e.target.value)}
            rows={2}
            placeholder={t('notes.placeholder')}
            className="min-h-[64px] flex-1 rounded-xl border border-[var(--premium-border)] bg-transparent px-3 py-2 text-sm outline-none focus:border-brand-400"
          />
          <Button type="submit" size="sm" disabled={create.isPending || !body.trim()}>
            <Send size={14} />
            {t('notes.add')}
          </Button>
        </form>

        {isLoading ? (
          <p className="text-sm text-[var(--premium-muted-text)]">{t('common.loading')}</p>
        ) : notes.length === 0 ? (
          <p className="text-sm text-[var(--premium-muted-text)]">{t('notes.empty')}</p>
        ) : (
          <ul className="space-y-3">
            {notes.map((n) => (
              <li
                key={n.id}
                className="rounded-xl border border-[var(--premium-border)] px-3 py-2"
              >
                <div className="flex items-start justify-between gap-2">
                  <div>
                    <p className="whitespace-pre-wrap text-sm text-[var(--premium-text)]">{n.body}</p>
                    <p className="mt-1 text-xs text-[var(--premium-label)]">
                      {n.created_by_user?.name || t('notes.unknownAuthor')} ·{' '}
                      {new Date(n.created_at).toLocaleString()}
                    </p>
                  </div>
                  <button
                    type="button"
                    className="rounded-lg p-1 text-[var(--premium-muted-text)] hover:bg-[var(--premium-hover-bg)] hover:text-red-600"
                    onClick={() => remove.mutate(n.id)}
                    aria-label={t('common.delete')}
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    </PermissionGate>
  )
}
