import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Search, MapPin, Beaker, ArrowRight, ShieldAlert, Info } from "lucide-react"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { fetchApi } from "@/lib/api-client"
import { cn } from "@/lib/utils"
import Link from "next/link"

interface Trial {
  id: number;
  nct_id: string;
  title: string;
  phase: string;
  status: string;
  locations: string;
  cancer_type: string;
}

export default async function ClinicalTrialsPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; location?: string }>
}) {
  const { q: searchQuery = "", location = "" } = await searchParams
  
  let trials: Trial[] = []
  try {
    trials = await fetchApi(`trials.php?q=${encodeURIComponent(searchQuery)}&location=${encodeURIComponent(location)}`)
  } catch (error) {
    console.error("Failed to fetch trials:", error)
  }

  return (
    <div className="flex min-h-screen flex-col">
      <main className="flex-1">
        <section className="bg-secondary/5 py-12 border-b">
          <div className="container mx-auto px-4">
            <div className="max-w-3xl space-y-6">
              <Badge variant="secondary" className="bg-secondary/10 text-secondary-foreground border-secondary/20">
                Navigator
              </Badge>
              <h1 className="text-4xl font-extrabold tracking-tight">Clinical Trials Navigator</h1>
              <p className="text-lg text-muted-foreground text-pretty">
                Search and filter simplified clinical trial data. Our tool helps you find potentially relevant studies
                to discuss with your oncology team.
              </p>
              <div className="bg-background border rounded-xl p-4 flex items-start gap-3 shadow-sm">
                <ShieldAlert className="h-5 w-5 text-destructive shrink-0 mt-0.5" />
                <p className="text-sm font-bold text-destructive">
                  IMPORTANT: Discuss trial eligibility and potential risks with your oncologist before taking any
                  action.
                </p>
              </div>
            </div>
          </div>
        </section>

        <section className="container mx-auto px-4 py-12">
          <TrialsContent trials={trials} searchQuery={searchQuery} location={location} />
        </section>
      </main>
    </div>
  )
}

function TrialsContent({ trials, searchQuery, location }: { trials: Trial[], searchQuery: string, location: string }) {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
      {/* Filters Sidebar */}
      <div className="lg:col-span-1 space-y-6">
        <form className="space-y-4">
          <h3 className="font-bold flex items-center gap-2">
            <Search className="h-4 w-4" />
            Filter Results
          </h3>
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Cancer Type</label>
              <Input name="q" placeholder="e.g. Breast Cancer" className="h-9" defaultValue={searchQuery} />
            </div>
            <div className="space-y-2">
              <label className="text-xs font-bold uppercase tracking-wider text-muted-foreground">Location</label>
              <Input name="location" placeholder="e.g. New York" className="h-9" defaultValue={location} />
            </div>
            <Button className="w-full h-9 font-bold">Apply Filters</Button>
          </div>
        </form>

        <Card className="bg-primary/5 border-none">
          <CardHeader className="p-4">
            <CardTitle className="text-sm flex items-center gap-2">
              <Info className="h-4 w-4 text-primary" />
              How to use this tool
            </CardTitle>
          </CardHeader>
          <CardContent className="p-4 pt-0 text-xs text-muted-foreground space-y-2">
            <p>1. Enter your specific diagnosis and location.</p>
            <p>2. Review the phase and status of matching trials.</p>
            <p>3. Print or share trial IDs (NCT numbers) with your doctor.</p>
          </CardContent>
        </Card>
      </div>

      {/* Trials Table */}
      <div className="lg:col-span-3">
        <Card className="border-none shadow-xl ring-1 ring-primary/5">
          <CardHeader className="border-b bg-muted/30">
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg flex items-center gap-2">
                <Beaker className="h-5 w-5 text-primary" />
                Available Trials ({trials.length})
              </CardTitle>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {trials.length > 0 ? (
              <div className="overflow-x-auto">
                <Table className="min-w-[600px] lg:min-w-0">
                  <TableHeader>
                    <TableRow className="hover:bg-transparent bg-muted/10">
                      <TableHead className="font-bold py-3 pl-6">Trial Details</TableHead>
                      <TableHead className="font-bold py-3 hidden sm:table-cell">Phase</TableHead>
                      <TableHead className="font-bold py-3">Status</TableHead>
                      <TableHead className="font-bold py-3 hidden md:table-cell">Location</TableHead>
                      <TableHead className="text-right font-bold py-3 pr-6">Action</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {trials.map((trial) => (
                      <TableRow key={trial.id} className="group transition-colors">
                        <TableCell className="py-4 pl-6 whitespace-normal min-w-[200px]">
                          <div className="space-y-2">
                            <p className="font-bold leading-snug group-hover:text-primary transition-colors">
                              {trial.title}
                            </p>
                            <div className="flex flex-wrap items-center gap-2">
                              <code className="text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono text-muted-foreground border">
                                {trial.nct_id}
                              </code>
                              <Badge variant="outline" className="text-[10px] py-0 h-4 border-primary/20 text-primary bg-primary/5">
                                {trial.cancer_type}
                              </Badge>
                              <div className="sm:hidden">
                                <Badge variant="secondary" className="text-[10px] py-0 h-4">
                                  {trial.phase}
                                </Badge>
                              </div>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="py-4 align-top hidden sm:table-cell">
                          <Badge variant="secondary" className="font-medium whitespace-nowrap">
                            {trial.phase}
                          </Badge>
                        </TableCell>
                        <TableCell className="py-4 align-top">
                          <div className="flex items-center gap-2 mt-1">
                            <span className={cn(
                              "h-2 w-2 rounded-full shrink-0",
                              trial.status === 'Recruiting' ? "bg-green-500" : "bg-amber-500"
                            )} />
                            <span className="text-sm font-medium whitespace-nowrap">{trial.status}</span>
                          </div>
                        </TableCell>
                        <TableCell className="py-4 align-top whitespace-normal min-w-[150px] hidden md:table-cell">
                          <div className="flex items-start gap-1.5 text-sm text-muted-foreground mt-0.5">
                            <MapPin className="h-3 w-3 shrink-0 mt-1" />
                            <span className="leading-relaxed">{trial.locations}</span>
                          </div>
                        </TableCell>
                        <TableCell className="text-right py-4 align-top pr-6">
                          <Button variant="ghost" size="sm" className="h-8 px-2 gap-1 font-bold hover:bg-primary hover:text-primary-foreground" asChild>
                            <Link href={`https://clinicaltrials.gov/study/${trial.nct_id}`} target="_blank">
                              <span className="hidden sm:inline">Details</span>
                              <ArrowRight className="h-3 w-3" />
                            </Link>
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="p-12 text-center">
                <p className="text-muted-foreground italic">No clinical trials found matching your criteria.</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
