'use client'

import { useState } from 'react'
import Link from 'next/link'
import { useParams } from 'next/navigation'
import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { ArrowLeft, Copy, Pencil } from 'lucide-react'
import { toast } from 'sonner'
import { api, type Site, type SiteLocation, type SiteShelf } from '@/lib/api'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { PermissionGate } from '@/components/auth/PermissionGate'
import { NotesTimeline } from '@/components/notes/NotesTimeline'

const statusVariant = (status: string) => {
  if (status === 'active' || status === 'completed') return 'success'
  if (status === 'disabled') return 'danger'
  return 'muted'
}

function countLocations(nodes: SiteLocation[] = []): number {
  return nodes.reduce((sum, n) => sum + 1 + countLocations(n.children ?? []), 0)
}

function LocationTree({ nodes, depth = 0 }: { nodes: SiteLocation[]; depth?: number }) {
  const { t } = useTranslation()
  if (!nodes.length) return null
  return (
    <ul className={depth === 0 ? 'space-y-2' : 'mt-2 space-y-1 border-l border-[var(--premium-border)] pl-3'}>
      {nodes.map((node) => (
        <li key={node.id}>
          <div className="text-sm">
            <span className="font-medium text-[var(--premium-text)]">{node.name}</span>
            <span className="ml-2 text-xs text-[var(--premium-muted-text)]">
              {t(`sites.locationTypes.${node.location_type}`, node.location_type)}
            </span>
          </div>
          {node.children?.length ? <LocationTree nodes={node.children} depth={depth + 1} /> : null}
        </li>
      ))}
    </ul>
  )
}

export function SiteDetailPage() {
  const { t } = useTranslation()
  const params = useParams()
  const id = params?.id as string
  const [tab, setTab] = useState<'overview' | 'locations' | 'shelf'>('overview')

  const dashboard = useQuery({
    queryKey: ['site-dashboard', id],
    queryFn: () => api.get<{ data: Site }>(`/sites/${id}/dashboard`),
    enabled: Boolean(id),
  })

  const shelf = useQuery({
    queryKey: ['site-shelf', id],
    queryFn: () => api.get<{ data: SiteShelf }>(`/sites/${id}/shelf`),
    enabled: Boolean(id) && tab === 'shelf',
  })

  const site = dashboard.data?.data.data

  if (dashboard.isLoading) {
    return (
      <div className="flex min-h-[40vh] items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-brand-500 border-t-transparent" />
      </div>
    )
  }

  if (!site) {
    return (
      <div className="premium-card rounded-2xl p-8 text-center">
        <p className="text-sm text-[var(--premium-muted-text)]">{t('common.noResults')}</p>
        <Link href="/sites" className="mt-4 inline-block text-sm font-semibold text-accent-600">
          {t('common.back')}
        </Link>
      </div>
    )
  }

  const copyQr = async () => {
    if (!site.qr_code) return
    try {
      await navigator.clipboard.writeText(site.qr_code)
      toast.success(t('sites.messages.qrCopied'))
    } catch {
      toast.error(t('common.somethingWentWrong'))
    }
  }

  const counts = site.counts ?? {
    assignments: site.assignments_count ?? 0,
    attendances: site.attendances_count ?? 0,
    locations: site.locations_count ?? countLocations(site.locations),
  }

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex flex-wrap items-start justify-between gap-3">
        <div>
          <Link
            href="/sites"
            className="mb-2 inline-flex items-center gap-1 text-xs font-semibold text-[var(--premium-muted-text)] hover:text-accent-600"
          >
            <ArrowLeft size={14} />
            {t('common.back')}
          </Link>
          <div className="flex flex-wrap items-center gap-3">
            <h1 className="premium-heading text-2xl font-bold">{site.name}</h1>
            <Badge variant={statusVariant(site.status)}>
              {t(`sites.status.${site.status}`, site.status)}
            </Badge>
          </div>
          <p className="mt-1 text-sm text-[var(--premium-muted-text)]">
            <span className="font-mono text-xs">{site.site_code}</span>
            {site.project ? (
              <>
                {' · '}
                <Link href={`/projects/${site.project.id}`} className="hover:text-accent-600">
                  {site.project.name}
                </Link>
              </>
            ) : null}
          </p>
        </div>
        <PermissionGate permission="sites.manage">
          <Link href={`/sites/${site.id}/edit`}>
            <Button size="sm" variant="secondary">
              <Pencil size={14} />
              {t('common.edit')}
            </Button>
          </Link>
        </PermissionGate>
      </div>

      <div className="animate-fade-in-up stagger-1 flex flex-wrap gap-2">
        {(
          [
            ['overview', t('sites.tabs.overview')],
            ['locations', t('sites.tabs.locations')],
            ['shelf', t('sites.tabs.shelf')],
          ] as const
        ).map(([key, label]) => (
          <button
            key={key}
            type="button"
            onClick={() => setTab(key)}
            className={`rounded-xl px-3 py-1.5 text-xs font-semibold transition ${
              tab === key
                ? 'bg-brand-600 text-white'
                : 'bg-[var(--premium-hover-bg)] text-[var(--premium-muted-text)] hover:text-[var(--premium-text)]'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {tab === 'overview' ? (
        <div className="animate-fade-in-up stagger-2 space-y-4">
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            {[
              { label: t('sites.progress'), value: `${site.progress ?? 0}%` },
              { label: t('nav.assignments'), value: String(counts.assignments) },
              { label: t('nav.attendances'), value: String(counts.attendances) },
              { label: t('sites.locationsCount'), value: String(counts.locations) },
            ].map((kpi) => (
              <div key={kpi.label} className="premium-card rounded-2xl p-4">
                <div className="text-xs font-semibold uppercase tracking-wide text-[var(--premium-muted-text)]">
                  {kpi.label}
                </div>
                <div className="mt-2 text-xl font-bold">{kpi.value}</div>
              </div>
            ))}
          </div>

          <div className="premium-card rounded-2xl p-5">
            <h2 className="text-sm font-semibold">{t('sites.qrCode')}</h2>
            <p className="mt-2 break-all font-mono text-sm text-[var(--premium-muted-text)]">
              {site.qr_code || '—'}
            </p>
            {site.qr_code ? (
              <Button size="sm" className="mt-3" onClick={copyQr}>
                <Copy size={14} />
                {t('sites.copyQr')}
              </Button>
            ) : null}
          </div>

          <NotesTimeline entityType="site" entityId={site.id} />
        </div>
      ) : null}

      {tab === 'locations' ? (
        <div className="animate-fade-in-up stagger-2 premium-card rounded-2xl p-5">
          <h2 className="mb-3 text-sm font-semibold">{t('sites.sections.locations')}</h2>
          {(site.locations ?? []).length === 0 ? (
            <p className="text-sm text-[var(--premium-muted-text)]">{t('sites.noLocations')}</p>
          ) : (
            <LocationTree nodes={site.locations ?? []} />
          )}
        </div>
      ) : null}

      {tab === 'shelf' ? (
        <div className="animate-fade-in-up stagger-2 premium-card rounded-2xl p-5">
          <h2 className="mb-1 text-sm font-semibold">{t('sites.shelfTitle')}</h2>
          <p className="mb-4 text-xs text-[var(--premium-muted-text)]">{t('sites.shelfPlaceholder')}</p>
          {shelf.isLoading ? (
            <div className="text-sm text-[var(--premium-muted-text)]">{t('common.loading')}</div>
          ) : (
            <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {(shelf.data?.data.data.folders ?? []).map((folder) => (
                <li
                  key={folder.name}
                  className="rounded-xl border border-[var(--premium-border)] px-4 py-3"
                >
                  <div className="font-semibold text-[var(--premium-text)]">{folder.name}</div>
                  <div className="mt-1 text-xs text-[var(--premium-muted-text)]">
                    {t('sites.shelfItems', { count: folder.count })}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
      ) : null}
    </div>
  )
}
