import { useMemo, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Eye, ExternalLink, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { pageBlockApi } from '@/lib/api/blocks'
import {
  createPage,
  fetchPage,
  updatePage,
} from '@/lib/api/pages'
import { handleServerError } from '@/lib/handle-server-error'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Main } from '@/components/layout/main'
import { PagesHeader } from './components/pages-header'
import { PageForm, type PageFormValues } from './components/page-form'
import { BlockManager } from '@/components/block-manager'
import { PreviewModal } from './components/preview-modal'

const FRONTEND_URL =
  (import.meta.env.VITE_FRONTEND_URL as string | undefined)?.replace(
    /\/$/,
    ''
  ) || 'http://localhost:3000'

export function PageEditorScreen({ pageId }: { pageId?: string }) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)

  const pageQuery = useQuery({
    queryKey: ['page', pageId],
    queryFn: () => fetchPage(pageId as string),
    enabled: Boolean(pageId),
  })

  const upsertMutation = useMutation({
    mutationFn: async (values: PageFormValues) => {
      const payload = {
        title: values.title,
        slug: values.slug,
        meta_title: values.metaTitle || null,
        meta_description: values.metaDescription || null,
        is_active: values.isActive,
      }

      if (pageId) {
        return updatePage(pageId, payload)
      }
      return createPage(payload)
    },
    onSuccess: async () => {
      toast.success('Sayfa kaydedildi')
      await queryClient.invalidateQueries({ queryKey: ['pages'] })
      if (pageId) {
        await queryClient.invalidateQueries({ queryKey: ['page', pageId] })
      }
      navigate({ to: '/pages' })
    },
    onError: handleServerError,
  })

  const pageRecord = pageQuery.data ?? null
  const isLoadingPage = Boolean(pageId) && !pageRecord && !pageQuery.isError

  function handlePreview() {
    if (!pageRecord) return
    const url = `${FRONTEND_URL}/kurumsal/${pageRecord.slug}`
    setPreviewUrl(url)
  }

  return (
    <>
      <PagesHeader />
      <Main className='space-y-6'>
        {isLoadingPage ? (
          <Card className='border-border/70 shadow-sm'>
            <CardContent className='flex min-h-64 items-center justify-center text-muted-foreground'>
              <div className='text-center'>
                <Loader2 className='mx-auto mb-3 size-6 animate-spin' />
                Sayfa bilgileri yükleniyor...
              </div>
            </CardContent>
          </Card>
        ) : (
          <>
            <PageForm
              key={pageRecord ? String(pageRecord.id) : 'create-page'}
              page={pageRecord}
              isEdit={Boolean(pageId)}
              isPending={upsertMutation.isPending || pageQuery.isFetching}
              onCancel={() => navigate({ to: '/pages' })}
              onSubmit={async (values) => {
                await upsertMutation.mutateAsync(values)
              }}
            />

            {pageRecord && (
              <>
                {/* Preview bar */}
                <div className='flex items-center justify-between rounded-2xl border border-border/70 bg-card px-4 py-3 shadow-sm'>
                  <div>
                    <p className='text-sm font-medium'>Sayfa Önizleme</p>
                    <p className='text-xs text-muted-foreground'>
                      Sayfanın frontend'deki görünümünü kontrol edin
                    </p>
                  </div>
                  <div className='flex gap-2'>
                    <Button
                      type='button'
                      variant='outline'
                      className='gap-2 rounded-xl'
                      onClick={handlePreview}
                    >
                      <Eye className='size-4' />
                      Önizle
                    </Button>
                    <Button
                      type='button'
                      variant='ghost'
                      size='icon'
                      className='rounded-xl'
                      onClick={() =>
                        window.open(
                          `${FRONTEND_URL}/kurumsal/${pageRecord.slug}`,
                          '_blank'
                        )
                      }
                    >
                      <ExternalLink className='size-4' />
                    </Button>
                  </div>
                </div>

                <BlockManager api={pageBlockApi(pageRecord.id)} />
              </>
            )}
          </>
        )}
      </Main>

      {/* Preview modal */}
      {previewUrl && (
        <PreviewModal
          url={previewUrl}
          title={pageRecord?.title ?? 'Sayfa'}
          onClose={() => setPreviewUrl(null)}
        />
      )}
    </>
  )
}
