"use client"

import React from "react"
import { usePathname, useParams } from "next/navigation"
import Link from "next/link"
import { Target } from "lucide-react"
import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { useTarget } from "@/hooks/use-targets"
import { useTranslations } from "next-intl"

/**
 * Target detail layout
 * Provides shared target information and navigation for all sub-pages
 */
export default function TargetLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const { id } = useParams<{ id: string }>()
  const pathname = usePathname()
  const t = useTranslations("pages.targetDetail")

  // Use React Query to get target data
  const {
    data: target,
    isLoading,
    error
  } = useTarget(Number(id))

  // Get currently active tab
  const getActiveTab = () => {
    if (pathname.includes("/subdomain")) return "subdomain"
    if (pathname.includes("/endpoints")) return "endpoints"
    if (pathname.includes("/websites")) return "websites"
    if (pathname.includes("/directories")) return "directories"
    if (pathname.includes("/vulnerabilities")) return "vulnerabilities"
    if (pathname.includes("/ip-addresses")) return "ip-addresses"
    return ""
  }

  // Tab path mapping
  const basePath = `/target/${id}`
  const tabPaths = {
    subdomain: `${basePath}/subdomain/`,
    endpoints: `${basePath}/endpoints/`,
    websites: `${basePath}/websites/`,
    directories: `${basePath}/directories/`,
    vulnerabilities: `${basePath}/vulnerabilities/`,
    "ip-addresses": `${basePath}/ip-addresses/`,
  }

  // Get counts for each tab from target data
  const counts = {
    subdomain: (target as any)?.summary?.subdomains || 0,
    endpoints: (target as any)?.summary?.endpoints || 0,
    websites: (target as any)?.summary?.websites || 0,
    directories: (target as any)?.summary?.directories || 0,
    vulnerabilities: (target as any)?.summary?.vulnerabilities?.total || 0,
    "ip-addresses": (target as any)?.summary?.ips || 0,
  }

  // Loading state
  if (isLoading) {
    return (
      <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
        {/* Page header skeleton */}
        <div className="flex items-center justify-between px-4 lg:px-6">
          <div className="w-full max-w-xl space-y-2">
            <div className="flex items-center gap-2">
              <Skeleton className="h-6 w-6 rounded-md" />
              <Skeleton className="h-7 w-48" />
            </div>
            <Skeleton className="h-4 w-72" />
          </div>
        </div>

        {/* Tabs navigation skeleton */}
        <div className="flex items-center justify-between px-4 lg:px-6">
          <div className="flex gap-2">
            <Skeleton className="h-9 w-20" />
            <Skeleton className="h-9 w-24" />
          </div>
        </div>
      </div>
    )
  }

  // Error state
  if (error) {
    return (
      <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
        <div className="flex items-center justify-center py-12">
          <div className="text-center">
            <Target className="mx-auto text-destructive mb-4" />
            <h3 className="text-lg font-semibold mb-2">{t("error.title")}</h3>
            <p className="text-muted-foreground">
              {error.message || t("error.message")}
            </p>
          </div>
        </div>
      </div>
    )
  }

  if (!target) {
    return (
      <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
        <div className="flex items-center justify-center py-12">
          <div className="text-center">
            <Target className="mx-auto text-muted-foreground mb-4" />
            <h3 className="text-lg font-semibold mb-2">{t("notFound.title")}</h3>
            <p className="text-muted-foreground">
              {t("notFound.message", { id })}
            </p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
      {/* Page header */}
      <div className="flex items-center justify-between px-4 lg:px-6">
        <div>
          <h2 className="text-2xl font-bold tracking-tight flex items-center gap-2">
            <Target />
            {target.name}
          </h2>
          <p className="text-muted-foreground">{target.description || t("noDescription")}</p>
        </div>
      </div>

      {/* Tabs navigation - Use Link to ensure progress bar is triggered */}
      <div className="flex items-center justify-between px-4 lg:px-6">
        <Tabs value={getActiveTab()} className="w-full">
          <TabsList>
            <TabsTrigger value="websites" asChild>
              <Link href={tabPaths.websites} className="flex items-center gap-0.5">
                Websites
                {counts.websites > 0 && (
                  <Badge variant="secondary" className="ml-1.5 h-5 min-w-5 rounded-full px-1.5 text-xs">
                    {counts.websites}
                  </Badge>
                )}
              </Link>
            </TabsTrigger>
            <TabsTrigger value="subdomain" asChild>
              <Link href={tabPaths.subdomain} className="flex items-center gap-0.5">
                Subdomains
                {counts.subdomain > 0 && (
                  <Badge variant="secondary" className="ml-1.5 h-5 min-w-5 rounded-full px-1.5 text-xs">
                    {counts.subdomain}
                  </Badge>
                )}
              </Link>
            </TabsTrigger>
            <TabsTrigger value="ip-addresses" asChild>
              <Link href={tabPaths["ip-addresses"]} className="flex items-center gap-0.5">
                IP Addresses
                {counts["ip-addresses"] > 0 && (
                  <Badge variant="secondary" className="ml-1.5 h-5 min-w-5 rounded-full px-1.5 text-xs">
                    {counts["ip-addresses"]}
                  </Badge>
                )}
              </Link>
            </TabsTrigger>
            <TabsTrigger value="endpoints" asChild>
              <Link href={tabPaths.endpoints} className="flex items-center gap-0.5">
                URLs
                {counts.endpoints > 0 && (
                  <Badge variant="secondary" className="ml-1.5 h-5 min-w-5 rounded-full px-1.5 text-xs">
                    {counts.endpoints}
                  </Badge>
                )}
              </Link>
            </TabsTrigger>
            <TabsTrigger value="directories" asChild>
              <Link href={tabPaths.directories} className="flex items-center gap-0.5">
                Directories
                {counts.directories > 0 && (
                  <Badge variant="secondary" className="ml-1.5 h-5 min-w-5 rounded-full px-1.5 text-xs">
                    {counts.directories}
                  </Badge>
                )}
              </Link>
            </TabsTrigger>
            <TabsTrigger value="vulnerabilities" asChild>
              <Link href={tabPaths.vulnerabilities} className="flex items-center gap-0.5">
                Vulnerabilities
                {counts.vulnerabilities > 0 && (
                  <Badge variant="secondary" className="ml-1.5 h-5 min-w-5 rounded-full px-1.5 text-xs">
                    {counts.vulnerabilities}
                  </Badge>
                )}
              </Link>
            </TabsTrigger>
          </TabsList>
        </Tabs>
      </div>

      {/* Sub-page content */}
      {children}
    </div>
  )
}
