"use client"

import { useState } from "react"
import type { ComparisonData } from "@/lib/types"
import { ComparisonRadarChart } from "@/components/comparison/radar-chart"
import { ComparisonTable } from "@/components/comparison/comparison-table"
import { ComparisonBarChart } from "@/components/comparison/bar-chart"
import { ScoreCard } from "@/components/comparison/score-card"
import { ProsConsCard } from "@/components/comparison/pros-cons-card"
import { useComparisonStream } from "@/hooks/use-comparison-stream"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Separator } from "@/components/ui/separator"
import { Skeleton } from "@/components/ui/skeleton"
import { Share2, ArrowLeft, Loader2, Trophy, AlertCircle } from "lucide-react"
import Link from "next/link"

interface ComparisonResultsClientProps {
  initialData: ComparisonData
}

export function ComparisonResultsClient({ initialData }: ComparisonResultsClientProps) {
  const [data] = useState<ComparisonData>(initialData)
  const { progress } = useComparisonStream()
  const isResearching = data.status === "researching" || progress?.status === "researching"

  const handleShare = async () => {
    const url = window.location.href
    await navigator.clipboard.writeText(url)
  }

  const winner = [...data.items].sort((a, b) => b.overallScore - a.overallScore)[0]

  if (data.status === "failed") {
    return (
      <div className="max-w-2xl mx-auto p-4 space-y-6">
        <div className="rounded-lg border border-red-200 bg-red-50 dark:border-red-900 dark:bg-red-950/30 p-6 space-y-4">
          <div className="flex items-start gap-3">
            <AlertCircle className="size-6 text-red-600 shrink-0 mt-0.5" />
            <div className="space-y-2">
              <h2 className="text-lg font-semibold text-red-800 dark:text-red-200">
                Comparison Failed
              </h2>
              <p className="text-sm text-red-700 dark:text-red-300">
                This comparison could not be completed. This may be due to a processing error or
                invalid input.
              </p>
            </div>
          </div>
          <Link href="/compare">
            <Button variant="outline" className="gap-2">
              <ArrowLeft className="size-4" />
              Try Again
            </Button>
          </Link>
        </div>
      </div>
    )
  }

  if (isResearching) {
    return (
      <div className="max-w-4xl mx-auto p-4 space-y-6">
        <div className="flex items-center gap-3">
          <Loader2 className="size-5 animate-spin text-primary" />
          <div>
            <h1 className="text-xl font-semibold">{data.title}</h1>
            <p className="text-sm text-muted-foreground">
              {progress.message || "Research in progress..."}
            </p>
          </div>
        </div>
        <div className="space-y-4">
          <Skeleton className="h-8 w-3/4" />
          <Skeleton className="h-64 w-full" />
          <Skeleton className="h-48 w-full" />
        </div>
      </div>
    )
  }

  return (
    <div className="max-w-6xl mx-auto p-4 space-y-6">
      <div className="flex items-start justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <Link href="/compare">
              <Button variant="ghost" size="icon-sm">
                <ArrowLeft className="size-4" />
              </Button>
            </Link>
            <h1 className="text-2xl font-bold tracking-tight">{data.title}</h1>
          </div>
          <p className="text-muted-foreground text-sm max-w-2xl">{data.summary}</p>
          <div className="flex flex-wrap gap-1.5 pt-1">
            {data.tags.map((tag) => (
              <Badge key={tag} variant="secondary" className="text-xs">
                {tag}
              </Badge>
            ))}
          </div>
        </div>
        <Button variant="outline" size="sm" onClick={handleShare}>
          <Share2 className="size-3.5" />
          Share
        </Button>
      </div>

      <Separator />

      <Tabs defaultValue="overview" className="w-full">
        <TabsList className="w-full justify-start">
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="charts">Charts</TabsTrigger>
          <TabsTrigger value="table">Table</TabsTrigger>
          <TabsTrigger value="details">Details</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-6 mt-6">
          {winner && (
            <div className="flex items-center gap-2 rounded-lg border border-emerald-200 bg-emerald-50 dark:border-emerald-900 dark:bg-emerald-950/30 p-3">
              <Trophy className="size-5 text-emerald-600" />
              <span className="text-sm font-medium">
                Top pick: <strong>{winner.name}</strong> ({winner.overallScore.toFixed(1)}/10)
              </span>
            </div>
          )}

          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {data.items.map((item, index) => (
              <ScoreCard
                key={item.name}
                item={item}
                index={index}
                dimensions={data.dimensions}
              />
            ))}
          </div>
        </TabsContent>

        <TabsContent value="charts" className="space-y-8 mt-6">
          <div className="space-y-2">
            <h3 className="text-lg font-semibold">Radar Chart</h3>
            <p className="text-sm text-muted-foreground">
              Visual comparison across all dimensions
            </p>
            <div className="rounded-lg border bg-card p-4">
              <ComparisonRadarChart items={data.items} dimensions={data.dimensions} />
            </div>
          </div>

          <div className="space-y-2">
            <h3 className="text-lg font-semibold">Score Comparison</h3>
            <p className="text-sm text-muted-foreground">
              Side-by-side bar chart of dimension scores
            </p>
            <div className="rounded-lg border bg-card p-4">
              <ComparisonBarChart items={data.items} dimensions={data.dimensions} />
            </div>
          </div>
        </TabsContent>

        <TabsContent value="table" className="mt-6">
          <ComparisonTable items={data.items} dimensions={data.dimensions} />
        </TabsContent>

        <TabsContent value="details" className="space-y-6 mt-6">
          <div className="grid gap-4 md:grid-cols-2">
            {data.items.map((item, index) => (
              <ProsConsCard key={item.name} item={item} index={index} />
            ))}
          </div>
        </TabsContent>
      </Tabs>
    </div>
  )
}
