import { useState } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from '@/shared/ui/toast-store'
import { Button } from '@/shared/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'
import { getInstructionIntro, listInstructionTabs } from '@/features/instructions/api'
import { deleteInstructionTab } from '@/features/admin/instructions/api'
import { InstructionIntroEditor } from '@/features/admin/instructions/InstructionIntroEditor'
import { InstructionTabFormDialog } from '@/features/admin/instructions/InstructionTabFormDialog'
import type { InstructionTabDto } from '@/shared/api/types'

export const Route = createFileRoute('/admin/instructions')({ component: AdminInstructionsPage })

function AdminInstructionsPage() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [editingTab, setEditingTab] = useState<InstructionTabDto | null>(null)

  const introQuery = useQuery({ queryKey: ['instruction-intro'], queryFn: getInstructionIntro })
  const tabsQuery = useQuery({ queryKey: ['instruction-tabs'], queryFn: listInstructionTabs })

  const deleteMutation = useMutation({
    mutationFn: deleteInstructionTab,
    onSuccess: async () => {
      toast.success(t('admin.instructions.tabDeleted'))
      await queryClient.invalidateQueries({ queryKey: ['instruction-tabs'] })
    },
    onError: () => toast.error(t('auth.genericError')),
  })

  return (
    <div className="flex flex-col gap-6">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t('admin.instructions.introTitle')}</CardTitle>
        </CardHeader>
        <CardContent>
          {introQuery.isLoading && <p className="text-sm text-muted-foreground">…</p>}
          {introQuery.data && <InstructionIntroEditor intro={introQuery.data} />}
        </CardContent>
      </Card>

      <div className="flex flex-col gap-4">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold tracking-tight">{t('admin.instructions.tabsTitle')}</h2>
          <InstructionTabFormDialog />
        </div>

        {tabsQuery.isLoading && <p className="text-sm text-muted-foreground">…</p>}

        {tabsQuery.isError && (
          <div className="flex items-center gap-2">
            <p className="text-sm text-muted-foreground">{t('auth.genericError')}</p>
            <Button variant="outline" size="sm" onClick={() => void tabsQuery.refetch()}>
              {t('activation.retry')}
            </Button>
          </div>
        )}

        {tabsQuery.data?.length === 0 && <p className="text-sm text-muted-foreground">{t('admin.instructions.tabsEmpty')}</p>}

        {tabsQuery.data && tabsQuery.data.length > 0 && (
          <div className="flex flex-col gap-2">
            {tabsQuery.data.map((tab) => (
              <div key={tab.id} className="flex items-center justify-between rounded-md border border-border px-3 py-2 text-sm">
                <div className="flex flex-col">
                  <span>{tab.title}</span>
                  <span className="text-xs text-muted-foreground">{t('admin.apps.sortOrder')}: {tab.sortOrder}</span>
                </div>
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={() => setEditingTab(tab)}>
                    {t('admin.roles.edit')}
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    disabled={deleteMutation.isPending}
                    onClick={() => {
                      if (confirm(t('admin.instructions.confirmDeleteTab'))) deleteMutation.mutate(tab.id)
                    }}
                  >
                    {t('admin.roles.delete')}
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {editingTab && (
        <InstructionTabFormDialog tab={editingTab} open={!!editingTab} onOpenChange={(open) => !open && setEditingTab(null)} />
      )}
    </div>
  )
}
