import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { Plus, Archive, RotateCcw, Trash2, LogIn, Users } from 'lucide-react'
import { api, setOrgOverride } from '@/lib/api'
import { ListPageShell } from '@/components/ListPageShell'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { SearchBar } from '@/components/SearchBar'
import { Button } from '@/components/Button'
import { Modal } from '@/components/Modal'
import { Field, TextInput } from '@/components/Field'
import { useCatalogList } from '@/lib/useCatalog'

const URL = '/api/super-admin/organizations'

interface OrgRow {
  id: string; name: string; countryCode: string
  isActive: boolean; isArchived: boolean; archivedAt: string | null
  createdAt: string; employeeCount: number; productCount: number; lastLoginAt: string | null
}

export function SuperAdminOrganizationsPage() {
  const navigate = useNavigate()
  const [archived, setArchived] = useState<boolean | null>(false)
  const list = useCatalogList<OrgRow>(URL, { archived: archived ?? undefined })
  const [archiveOf, setArchiveOf] = useState<OrgRow | null>(null)
  const [deleteOf, setDeleteOf] = useState<OrgRow | null>(null)
  const [confirmName, setConfirmName] = useState('')

  const archive = async () => {
    if (!archiveOf || confirmName !== archiveOf.name) return
    await api.post(`${URL}/${archiveOf.id}/archive`, { confirmationName: confirmName })
    setArchiveOf(null); setConfirmName('')
    list.refetch()
  }
  const restore = async (id: string) => {
    await api.post(`${URL}/${id}/restore`)
    list.refetch()
  }
  const hardDelete = async () => {
    if (!deleteOf || confirmName !== deleteOf.name) return
    await api.delete(`${URL}/${deleteOf.id}`, { data: { confirmationName: confirmName } })
    setDeleteOf(null); setConfirmName('')
    list.refetch()
  }

  // Период до возможности удалить навсегда — читаем из системных настроек.
  const settings = useQuery({
    queryKey: ['/api/super-admin/settings'],
    queryFn: async () => (await api.get<{ archiveRetentionDays: number }>('/api/super-admin/settings')).data,
  })
  const retentionDays = settings.data?.archiveRetentionDays ?? 30
  const canDelete = (iso: string | null) => {
    if (!iso) return false
    if (retentionDays === 0) return true
    return new Date(iso).getTime() < Date.now() - retentionDays * 24 * 60 * 60 * 1000
  }
  const daysSinceArchive = (iso: string | null) => {
    if (!iso) return 0
    return Math.floor((Date.now() - new Date(iso).getTime()) / (24 * 60 * 60 * 1000))
  }

  return (
    <>
      <ListPageShell
        title="Организации"
        description="Управление всеми организациями системы. Действия логируются в журнал."
        actions={
          <>
            <SearchBar value={list.search} onChange={list.setSearch} />
            <select value={archived === null ? 'all' : String(archived)}
              onChange={(e) => setArchived(e.target.value === 'all' ? null : e.target.value === 'true')}
              className="h-9 px-2 rounded-md border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-sm">
              <option value="false">Активные</option>
              <option value="true">Архив</option>
              <option value="all">Все</option>
            </select>
            <Button onClick={() => navigate('/super-admin/organizations/new')}>
              <Plus className="w-4 h-4" /> Создать
            </Button>
          </>
        }
        footer={list.data && list.data.total > 0 && (
          <Pagination page={list.page} pageSize={list.data.pageSize} total={list.data.total} onPageChange={list.setPage} />
        )}
      >
        <DataTable
          rows={list.data?.items ?? []}
          isLoading={list.isLoading}
          rowKey={(r) => r.id}
          sortKey={list.sortKey}
          sortOrder={list.sortOrder}
          onSortChange={list.setSort}
          onRowDoubleClick={(r) => setOrgOverride({ id: r.id, name: r.name }, { redirectTo: '/dashboard' })}
          columns={[
            { header: 'Название', cell: (r) => (
              <div>
                <div className="font-medium">{r.name}</div>
                <div className="text-xs text-slate-400">{r.countryCode}</div>
              </div>
            )},
            { header: 'Создана', width: '140px', cell: (r) => new Date(r.createdAt).toLocaleDateString('ru') },
            { header: 'Сотрудники', width: '110px', className: 'text-right', cell: (r) => r.employeeCount },
            { header: 'Товары', width: '110px', className: 'text-right', cell: (r) => r.productCount },
            { header: 'Last login', width: '140px', cell: (r) => r.lastLoginAt ? new Date(r.lastLoginAt).toLocaleDateString('ru') : '—' },
            { header: 'Статус', width: '120px', cell: (r) => r.isArchived
              ? <span className="text-xs px-1.5 py-0.5 rounded bg-amber-100 text-amber-700">Архив</span>
              : <span className="text-xs text-emerald-600">Активна</span> },
            { header: '', width: '160px', cell: (r) => (
              <div className="flex gap-1.5" onClick={(e) => e.stopPropagation()}>
                {!r.isArchived && (
                  <button title="Открыть как… (read-only)"
                    onClick={() => setOrgOverride({ id: r.id, name: r.name }, { redirectTo: '/dashboard' })}
                    className="p-1.5 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded">
                    <LogIn className="w-4 h-4" />
                  </button>
                )}
                <button title="Сотрудники организации"
                  onClick={() => navigate(`/super-admin/organizations/${r.id}/employees`)}
                  className="p-1.5 text-indigo-600 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 rounded">
                  <Users className="w-4 h-4" />
                </button>
                {!r.isArchived ? (
                  <button title="Архивировать" onClick={() => { setArchiveOf(r); setConfirmName('') }}
                    className="p-1.5 text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded">
                    <Archive className="w-4 h-4" />
                  </button>
                ) : (
                  <>
                    <button title="Восстановить" onClick={() => restore(r.id)}
                      className="p-1.5 text-emerald-600 hover:bg-emerald-50 dark:hover:bg-emerald-900/20 rounded">
                      <RotateCcw className="w-4 h-4" />
                    </button>
                    <button title={canDelete(r.archivedAt)
                        ? 'Удалить навсегда'
                        : `Доступно через ${Math.max(0, retentionDays - daysSinceArchive(r.archivedAt))} дн. (retention ${retentionDays})`}
                      disabled={!canDelete(r.archivedAt)}
                      onClick={() => canDelete(r.archivedAt) && (setDeleteOf(r), setConfirmName(''))}
                      className="p-1.5 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded disabled:opacity-30 disabled:cursor-not-allowed">
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </>
                )}
              </div>
            )},
          ]}
        />
      </ListPageShell>

      <Modal open={!!archiveOf} onClose={() => setArchiveOf(null)}
        title="Архивировать организацию"
        footer={<>
          <Button variant="secondary" onClick={() => setArchiveOf(null)}>Отмена</Button>
          <Button variant="danger" onClick={archive} disabled={confirmName !== archiveOf?.name}>Архивировать</Button>
        </>}>
        {archiveOf && (
          <div className="space-y-3">
            <p className="text-sm text-slate-600 dark:text-slate-400">
              Организация <strong>{archiveOf.name}</strong> станет недоступной пользователям, но
              данные сохранятся. Удалить навсегда можно через 30 дней.
            </p>
            <Field label={`Введи название «${archiveOf.name}» для подтверждения`}>
              <TextInput value={confirmName} onChange={(e) => setConfirmName(e.target.value)} />
            </Field>
          </div>
        )}
      </Modal>

      <Modal open={!!deleteOf} onClose={() => setDeleteOf(null)}
        title="Удалить организацию навсегда"
        footer={<>
          <Button variant="secondary" onClick={() => setDeleteOf(null)}>Отмена</Button>
          <Button variant="danger" onClick={hardDelete} disabled={confirmName !== deleteOf?.name}>Удалить навсегда</Button>
        </>}>
        {deleteOf && (
          <div className="space-y-3">
            <p className="text-sm text-red-600">
              Все данные организации <strong>{deleteOf.name}</strong> будут удалены безвозвратно.
              Действие необратимо.
            </p>
            <Field label={`Введи название «${deleteOf.name}» точно для подтверждения`}>
              <TextInput value={confirmName} onChange={(e) => setConfirmName(e.target.value)} />
            </Field>
          </div>
        )}
      </Modal>
    </>
  )
}
