"use client"

import React, { useState } from "react"
import {
  CalendarDays,
  ChevronDown,
  GitBranch,
  GitMerge,
  GitPullRequestClosed,
  GitPullRequest,
} from "lucide-react"
import { useRouter, useSearchParams } from "next/navigation"
import dynamic from "next/dynamic"
import { Skeleton } from "@/components/ui/skeleton"
import { useOutsideClick } from "../hooks/useOutsideClick"

const PullRequestActivityBarChart = dynamic(
  () => import("./PullRequestActivityBarChart").then(mod => mod.PullRequestActivityBarChart),
  {
    ssr: false,
    loading: () => <Skeleton className="h-full w-full rounded-md" />,
  },
)

interface CompactPullRequestActivityCardProps {
  prData: Array<{
    month: string
    pr_created: number
    pr_merged: number
    pr_closed: number
  }>
  selectedYear: number
  onYearChange?: (year: number) => void
  className?: string
}

export const CompactPullRequestActivityCard: React.FC<CompactPullRequestActivityCardProps> = ({
  prData,
  selectedYear,
  onYearChange,
  className,
}) => {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [isYearDropdownOpen, setIsYearDropdownOpen] = useState(false)

  const handleYearChange = (year: number) => {
    if (onYearChange) {
      onYearChange(year)
    } else {
      const params = new URLSearchParams(searchParams.toString())
      params.set("year", String(year))
      router.push(`?${params.toString()}`)
    }
  }
  const yearDropdownRef = useOutsideClick(() => setIsYearDropdownOpen(false))

  const safePrData = Array.isArray(prData) ? prData : []

  const totalCreated = Math.round(
    safePrData.reduce((sum, item) => sum + (item?.pr_created || 0), 0),
  )
  const totalMerged = Math.round(safePrData.reduce((sum, item) => sum + (item?.pr_merged || 0), 0))
  const totalClosed = Math.round(safePrData.reduce((sum, item) => sum + (item?.pr_closed || 0), 0))

  const baseYear = 2025
  const currentYear = new Date().getFullYear()

  const availableYears = Array.from(
    { length: Math.max(1, currentYear - baseYear + 1) },
    (_, i) => baseYear + i,
  ).filter(year => year <= currentYear)

  return (
    <div
      className={`bg-card rounded-xl border border-border p-4 hover:shadow-md transition-all duration-300 hover:border-primary/20 h-full flex flex-col ${className || ""}`}
    >
      <div className="flex items-center justify-between mb-3">
        <div>
          <h3 className="text-sm font-semibold mb-0.5">Pull Request Activity</h3>
          <div className="text-xs text-muted-foreground">Monthly PR events</div>
        </div>

        <div className="relative" ref={yearDropdownRef}>
          <button
            onClick={() => setIsYearDropdownOpen(!isYearDropdownOpen)}
            className="flex items-center gap-1 px-2 py-1 text-xs bg-background border border-border rounded-md hover:border-primary/50 transition-colors"
            disabled={availableYears.length <= 1}
          >
            <CalendarDays size={12} className="text-muted-foreground" />
            <span>{selectedYear}</span>
            {availableYears.length > 1 && (
              <ChevronDown
                size={12}
                className={`transition-transform text-muted-foreground ${isYearDropdownOpen ? "rotate-180" : ""}`}
              />
            )}
          </button>

          {isYearDropdownOpen && availableYears.length > 1 && (
            <div className="absolute right-0 z-10 mt-1 w-32 bg-card rounded-md shadow-lg overflow-hidden border border-border animate-in fade-in-50 slide-in-from-top-5">
              <div className="py-1">
                {availableYears.map(year => (
                  <button
                    key={year}
                    onClick={() => {
                      handleYearChange(year)
                      setIsYearDropdownOpen(false)
                    }}
                    className={`w-full px-3 py-1.5 text-left hover:bg-muted flex items-center ${selectedYear === year ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 h-4 mr-1.5 flex items-center justify-center">
                      {selectedYear === year && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    {year}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="flex justify-between text-xs mb-3">
        <div className="flex items-center gap-1">
          <div className="w-5 h-5 rounded-md bg-blue-100 flex items-center justify-center text-blue-600">
            <GitBranch size={12} />
          </div>
          <div>
            <div className="font-medium text-blue-600">Created</div>
            <div className="font-semibold text-blue-700">{totalCreated}</div>
          </div>
        </div>

        <div className="flex items-center gap-1">
          <div className="w-5 h-5 rounded-md bg-green-100 flex items-center justify-center text-green-600">
            <GitMerge size={12} />
          </div>
          <div>
            <div className="font-medium text-green-600">Merged</div>
            <div className="font-semibold text-green-700">{totalMerged}</div>
          </div>
        </div>

        <div className="flex items-center gap-1">
          <div className="w-5 h-5 rounded-md bg-red-100 flex items-center justify-center text-red-600">
            <GitPullRequestClosed size={12} />
          </div>
          <div>
            <div className="font-medium text-red-600">Closed</div>
            <div className="font-semibold text-red-700">{totalClosed}</div>
          </div>
        </div>
      </div>

      <div className="flex-1 min-h-0">
        {safePrData.length > 0 ? (
          <PullRequestActivityBarChart data={safePrData} height={"100%"} />
        ) : (
          <div className="flex flex-col justify-center items-center h-full bg-muted/10 rounded-md border border-dashed border-border/50">
            <GitPullRequest size={20} className="text-muted-foreground/30 mb-2" />
            <p className="text-xs text-muted-foreground text-center">
              No PR activity data for {selectedYear}
            </p>
          </div>
        )}
      </div>
    </div>
  )
}
