"use client"

import { useParams, useRouter } from "next/navigation"
import { useMutation, useQuery } from "convex/react"
import { api } from "@/convex/_generated/api"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Settings } from "lucide-react"
import * as React from "react"

function formatDate(timestamp?: number) {
  if (!timestamp) return "Not analyzed yet";
  return new Date(timestamp).toLocaleString();
}

export default function DataSourceDetailPage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  const dataSourceId = params?.id
  const dataSource = useQuery(
    api.dataSources.getById,
    dataSourceId ? { dataSourceId: dataSourceId as any } : "skip"
  )
  const analysis = useQuery(
    api.analyses.getLatestByDataSource,
    dataSourceId ? { dataSourceId: dataSourceId as any } : "skip"
  )
  const removeDataSource = useMutation(api.dataSources.remove)
  const [isDeleting, setIsDeleting] = React.useState(false)
  const [isDialogOpen, setIsDialogOpen] = React.useState(false)

  if (dataSource === undefined) {
    return (
      <div className="p-8">
        <div className="text-sm text-muted-foreground">Loading data source…</div>
      </div>
    )
  }

  if (!dataSource) {
    return (
      <div className="p-8">
        <h1 className="text-2xl font-semibold">Data source not found</h1>
        <p className="mt-2 text-sm text-muted-foreground">
          This data source may have been removed or you no longer have access.
        </p>
      </div>
    )
  }

  const statusVariant =
    dataSource.analysisStatus === "completed"
      ? "secondary"
      : dataSource.analysisStatus === "failed"
      ? "destructive"
      : "outline"

  return (
    <div className="flex flex-1 flex-col gap-6 p-8">
      <div className="flex flex-col gap-2">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <h1 className="text-3xl font-semibold">
            {dataSource.name || "Data Source"}
          </h1>
          <div className="flex items-center gap-2">
            <Badge variant={statusVariant}>
              {dataSource.analysisStatus}
            </Badge>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setIsDialogOpen(true)}
              aria-label="Data source settings"
            >
              <Settings className="size-4" />
            </Button>
          </div>
        </div>
        <p className="text-sm text-muted-foreground">{dataSource.url}</p>
        <div className="flex flex-wrap gap-3 text-xs text-muted-foreground">
          <span>Last analyzed: {formatDate(dataSource.lastAnalyzedAt)}</span>
          {dataSource.lastError && (
            <span className="text-destructive">
              Error: {dataSource.lastError}
            </span>
          )}
        </div>
      </div>

      {analysis ? (
        <>
          <div className="grid gap-4 md:grid-cols-3">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm">Features</CardTitle>
              </CardHeader>
              <CardContent className="text-2xl font-semibold">
                {analysis.features.length}
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm">Keywords</CardTitle>
              </CardHeader>
              <CardContent className="text-2xl font-semibold">
                {analysis.keywords.length}
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm">Personas</CardTitle>
              </CardHeader>
              <CardContent className="text-2xl font-semibold">
                {analysis.personas.length}
              </CardContent>
            </Card>
          </div>

          <Card>
            <CardHeader>
              <CardTitle className="text-base">Overview</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2 text-sm text-muted-foreground">
              <div>
                <span className="font-medium text-foreground">Product:</span>{" "}
                {analysis.productName}
              </div>
              <div>
                <span className="font-medium text-foreground">Tagline:</span>{" "}
                {analysis.tagline}
              </div>
              <div>
                <span className="font-medium text-foreground">Category:</span>{" "}
                {analysis.category}
              </div>
              <div>
                <span className="font-medium text-foreground">Positioning:</span>{" "}
                {analysis.positioning}
              </div>
              <div className="pt-2">{analysis.description}</div>
            </CardContent>
          </Card>

          <div className="grid gap-4 lg:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Top Features</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                {analysis.features.slice(0, 6).map((feature) => (
                  <div key={feature.name}>
                    <div className="font-medium">{feature.name}</div>
                    <div className="text-muted-foreground">
                      {feature.description}
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Pain Points</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                {analysis.problemsSolved.slice(0, 6).map((problem) => (
                  <div key={problem.problem}>
                    <div className="font-medium">{problem.problem}</div>
                    <div className="text-muted-foreground">
                      Severity: {problem.severity} · {problem.emotionalImpact}
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>
          </div>

          <div className="grid gap-4 lg:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Personas</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                {analysis.personas.slice(0, 4).map((persona) => (
                  <div key={`${persona.name}-${persona.role}`}>
                    <div className="font-medium">
                      {persona.name} · {persona.role}
                    </div>
                    <div className="text-muted-foreground">
                      {persona.industry} · {persona.companySize}
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Keywords</CardTitle>
              </CardHeader>
              <CardContent className="flex flex-wrap gap-2">
                {analysis.keywords.slice(0, 12).map((keyword) => (
                  <Badge key={keyword.term} variant="outline">
                    {keyword.term}
                  </Badge>
                ))}
              </CardContent>
            </Card>
          </div>
        </>
      ) : (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Analysis</CardTitle>
          </CardHeader>
          <CardContent className="text-sm text-muted-foreground">
            No analysis available yet. Trigger a new analysis to populate this
            data source.
          </CardContent>
        </Card>
      )}

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete data source</DialogTitle>
            <DialogDescription>
              This removes the data source and its analyses from the project. This
              cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsDialogOpen(false)}
              disabled={isDeleting}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={async () => {
                if (!dataSourceId) return
                setIsDeleting(true)
                await removeDataSource({ dataSourceId: dataSourceId as any })
                router.push("/dashboard")
              }}
              disabled={isDeleting}
            >
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
