'use client'

import { useState } from 'react'
import Link from 'next/link'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Plus, Download } from 'lucide-react'
import { toast } from 'sonner'
import { api, type PaginatedResponse, type Employee } from '@/lib/api'
import { DataTable, type BulkAction } from '@/components/DataTable'
import { Button } from '@/components/ui/Button'
import { Badge } from '@/components/ui/Badge'
import { Select } from '@/components/ui/Select'
import { formatDate } from '@/lib/utils'

export function EmployeesPage() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')
  const [page, setPage] = useState(1)
  const [selected, setSelected] = useState<number[]>([])
  const [exporting, setExporting] = useState(false)

  const { data, isLoading } = useQuery({
    queryKey: ['employees', search, status, page],
    queryFn: () =>
      api.get<PaginatedResponse<Employee>>('/employees', {
        params: { search: search || undefined, status: status || undefined, page, per_page: 25 },
      }),
  })

  const bulkDisable = useMutation({
    mutationFn: (ids: number[]) => api.post('/employees/bulk-disable', { ids }),
    onSuccess: (_, ids) => {
      toast.success(t('employees.messages.disableSuccess', { count: ids.length }))
      setSelected([])
      queryClient.invalidateQueries({ queryKey: ['employees'] })
    },
    onError: () => toast.error(t('employees.messages.disableFailed')),
  })

  const bulkDelete = useMutation({
    mutationFn: (ids: number[]) => api.delete('/employees/bulk-delete', { data: { ids } }),
    onSuccess: (_, ids) => {
      toast.success(t('employees.messages.deleteSuccess', { count: ids.length }))
      setSelected([])
      queryClient.invalidateQueries({ queryKey: ['employees'] })
    },
    onError: () => toast.error(t('employees.messages.deleteFailed')),
  })

  const handleExport = async () => {
    setExporting(true)
    try {
      const res = await api.get('/employees/export', {
        params: { search: search || undefined, status: status || undefined },
        responseType: 'blob',
      })
      const url = window.URL.createObjectURL(new Blob([res.data as BlobPart]))
      const a = document.createElement('a')
      a.href = url
      a.download = `employees_${new Date().toISOString().slice(0, 10)}.csv`
      a.click()
      window.URL.revokeObjectURL(url)
      toast.success(t('employees.messages.exportSuccess'))
    } catch {
      toast.error(t('employees.messages.exportFailed'))
    } finally {
      setExporting(false)
    }
  }

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

  const statusOptions = [
    { value: '', label: t('common.allStatuses') },
    ...(['active', 'inactive', 'on_leave', 'terminated'] as const).map((value) => ({
      value,
      label: t(`employees.statuses.${value}`),
    })),
  ]

  const bulkActions: BulkAction[] = [
    { label: t('common.disable'), variant: 'warning', onClick: (ids) => bulkDisable.mutate(ids) },
    {
      label: t('common.delete'),
      variant: 'danger',
      onClick: (ids) => {
        if (window.confirm(t('employees.messages.deleteConfirm', { count: ids.length }))) {
          bulkDelete.mutate(ids)
        }
      },
    },
  ]

  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('employees.title')}</h1>
        <div className="flex items-center gap-2">
          <Button
            variant="secondary"
            size="sm"
            onClick={handleExport}
            disabled={exporting}
          >
            <Download size={14} />
            {exporting ? t('common.exporting') : t('common.exportCsv')}
          </Button>
          <Link href="/employees/new">
            <Button size="sm">
              <Plus size={14} />
              {t('employees.create')}
            </Button>
          </Link>
        </div>
      </div>

      <div className="animate-fade-in-up stagger-1">
        <DataTable
          data={employees}
          loading={isLoading}
          selected={selected}
          onSelect={setSelected}
          bulkActions={bulkActions}
          emptyMessage={t('common.noResults')}
          onSearch={(q) => { setSearch(q); setPage(1) }}
          searchValue={search}
          searchPlaceholder={t('common.searchEmployees')}
          toolbar={
            <Select
              value={status}
              onChange={(e) => { setStatus(e.target.value); setPage(1) }}
              options={statusOptions}
            />
          }
          pagination={meta}
          onPageChange={setPage}
          columns={[
            { key: 'employee_code', header: t('common.code'), className: 'font-mono text-xs' },
            { key: 'full_name', header: t('employees.fullName') },
            {
              key: 'role',
              header: t('employees.role'),
              render: (r) => (
                <span>{t(`employees.roles.${r.role}`, r.role)}</span>
              ),
            },
            { key: 'department', header: t('employees.department'), render: (r) => r.department || '—' },
            {
              key: 'status',
              header: t('common.status'),
              render: (r) => (
                <Badge variant={r.status === 'active' ? 'success' : 'muted'}>
                  {t(`employees.statuses.${r.status}`, r.status)}
                </Badge>
              ),
            },
            {
              key: 'joining_date',
              header: t('employees.joiningDate'),
              render: (r) => formatDate(r.joining_date),
            },
            {
              key: 'actions',
              header: t('common.actions'),
              className: 'text-right',
              render: (r) => (
                <Link
                  href={`/employees/${r.id}/edit`}
                className="rounded-lg px-2 py-1 text-xs font-semibold text-accent-600 transition-colors hover:bg-[var(--premium-hover-bg)] hover:text-accent-500 dark:text-accent-400 dark:hover:text-accent-300"
                >
                  {t('common.edit')}
                </Link>
              ),
            },
          ]}
        />
      </div>
    </div>
  )
}
