"use client"

import { useState, useMemo } from "react"
import {
  Clock,
  GitPullRequest,
  Search,
  ChevronDown,
  X,
  RefreshCw,
  Filter,
  ArrowUpDown,
  BookOpen,
} from "lucide-react"
import Image from "next/image"
import { Card } from "@/components/ui/card"
import Link from "next/link"
import { useRouter } from "next/navigation"
import type { RepositoryWithUsage } from "@/app/(dashboard)/dashboard/action"

/** Serialized version for server→client boundary (Dates become ISO strings) */
type SerializedRepository = Omit<RepositoryWithUsage, "created_at" | "last_optimized"> & {
  created_at: string
  last_optimized: string | null
}
import { useOutsideClick } from "@/components/hooks/useOutsideClick"

function SearchBar({
  searchQuery,
  setSearchQuery,
}: {
  searchQuery: string
  setSearchQuery: (value: string) => void
}) {
  return (
    <div className="relative flex-1 group">
      <div className="relative">
        <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
          <Search
            size={18}
            className="text-muted-foreground/70 group-focus-within:text-primary transition-colors"
          />
        </div>
        <input
          type="text"
          placeholder="Search repositories..."
          value={searchQuery}
          onChange={e => setSearchQuery(e.target.value)}
          className="block w-full rounded-xl border border-border bg-background/60 p-3 pl-10 text-foreground focus:border-primary focus:ring-1 focus:ring-primary transition-all duration-200"
        />
        {searchQuery && (
          <button
            className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground hover:text-foreground"
            onClick={() => setSearchQuery("")}
          >
            <X size={18} className="opacity-70 hover:opacity-100" />
          </button>
        )}
      </div>
    </div>
  )
}

function RepositoryCard({ repo }: { repo: SerializedRepository }) {
  return (
    <Link href={`/repositories/${repo.id}`}>
      <Card
        key={repo.id}
        className="bg-card bg-muted/5 rounded-xl border border-border hover:border-primary/30 hover:shadow-md hover:shadow-primary/5 transition-all duration-300 overflow-hidden group"
      >
        <div className="p-5">
          <div className="flex items-start">
            <div className="mr-3 flex-shrink-0">
              {repo.avatarUrl ? (
                <div className="w-9 h-9 sm:w-11 sm:h-11 rounded-full overflow-hidden border-2 border-border/50 group-hover:border-primary/20 transition-colors">
                  <Image
                    src={repo.avatarUrl}
                    alt={`${repo.organization} avatar`}
                    width={44}
                    height={44}
                    className="object-cover w-full h-full"
                  />
                </div>
              ) : (
                <div className="w-9 h-9 sm:w-11 sm:h-11 rounded-full bg-gradient-to-br from-primary/10 to-primary/30 flex items-center justify-center border-2 border-border group-hover:from-primary/20 group-hover:to-primary/40 transition-colors">
                  <span className="text-primary font-semibold">
                    {repo.name?.substring(0, 1).toUpperCase() || "?"}
                  </span>
                </div>
              )}
            </div>

            <div className="flex-1 min-w-0">
              <div className="flex items-center flex-wrap gap-1">
                <h3 className="text-sm sm:text-base font-semibold text-primary hover:underline truncate">
                  {repo.name || "Unknown Repository"}
                </h3>

                <span
                  className={`ml-1 px-1.5 sm:px-2 py-0.5 text-xs font-medium rounded-full ${repo.is_private ? "bg-amber-100 text-amber-700" : "bg-emerald-100 text-emerald-700"}`}
                >
                  {repo.is_private ? "Private" : "Public"}
                </span>
              </div>

              <p className="text-xs sm:text-sm text-muted-foreground mb-2">
                {repo.full_name || repo.name}
              </p>

              <div className="flex items-center flex-wrap gap-1.5 sm:gap-2">
                <span
                  className={`inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full text-xs ${repo.is_active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"}`}
                >
                  <span
                    className={`inline-block w-1.5 sm:w-2 h-1.5 sm:h-2 rounded-full ${repo.is_active ? "bg-green-500" : "bg-gray-400"} mr-1 sm:mr-1.5`}
                  ></span>
                  <span>{repo.is_active ? "Active" : "Inactive"}</span>
                </span>

                {repo.has_github_action && (
                  <span className="inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full bg-blue-50 text-xs text-blue-700">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      viewBox="0 0 16 16"
                      width="10"
                      height="10"
                      className="mr-1 fill-current sm:w-3 sm:h-3"
                    >
                      <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path>
                    </svg>
                    Action
                  </span>
                )}

                {repo.membersCount !== undefined && repo.membersCount > 0 && (
                  <span className="inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full bg-indigo-50 text-xs text-indigo-700">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="10"
                      height="10"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="mr-1 sm:w-3 sm:h-3"
                    >
                      <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                      <circle cx="9" cy="7" r="4"></circle>
                      <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                      <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                    </svg>
                    {repo.membersCount}
                  </span>
                )}
              </div>
            </div>
          </div>

          {repo.last_optimized && (
            <div className="mt-3 sm:mt-4 text-xs text-muted-foreground flex items-center">
              <Clock size={10} className="mr-1 sm:w-3 sm:h-3" />
              Last optimized: {new Date(repo.last_optimized).toLocaleDateString()}
            </div>
          )}
        </div>
      </Card>
    </Link>
  )
}

export function RepositoryList({ repositories }: { repositories: SerializedRepository[] }) {
  const router = useRouter()
  const [searchQuery, setSearchQuery] = useState("")
  const [filter, setFilter] = useState<"all" | "active" | "public" | "private">("all")
  const [isFilterDropdownOpen, setIsFilterDropdownOpen] = useState(false)
  const [sortBy, setSortBy] = useState<"name">("name")
  const [isSortDropdownOpen, setIsSortDropdownOpen] = useState(false)
  const [isRefreshing, setIsRefreshing] = useState(false)

  const filterDropdownRef = useOutsideClick(() => setIsFilterDropdownOpen(false))
  const sortDropdownRef = useOutsideClick(() => setIsSortDropdownOpen(false))

  const getSortLabel = (sortType: string) => {
    switch (sortType) {
      case "name":
        return "Name"
      default:
        return "Last Optimized"
    }
  }

  const handleRefresh = () => {
    if (isRefreshing) return
    setIsRefreshing(true)
    router.refresh()
    // Reset after a short delay since router.refresh() doesn't provide a completion callback
    setTimeout(() => setIsRefreshing(false), 2000)
  }

  const filteredRepositories = useMemo(() => {
    if (!repositories || !Array.isArray(repositories)) {
      return []
    }

    let repos = repositories.filter(repo => {
      if (!repo) return false

      const matchesSearch =
        searchQuery === "" ||
        (repo.name && repo.name.toLowerCase().includes(searchQuery.toLowerCase())) ||
        (repo.full_name && repo.full_name.toLowerCase().includes(searchQuery.toLowerCase())) ||
        (repo.organization && repo.organization.toLowerCase().includes(searchQuery.toLowerCase()))

      if (!matchesSearch) return false

      switch (filter) {
        case "active":
          return repo.is_active
        case "public":
          return !repo.is_private
        case "private":
          return repo.is_private
        default:
          return true
      }
    })

    switch (sortBy) {
      case "name":
        repos = repos.sort((a, b) => {
          const nameA = a?.name || ""
          const nameB = b?.name || ""
          return nameA.localeCompare(nameB)
        })
        break
    }

    return repos
  }, [repositories, searchQuery, filter, sortBy])

  return (
    <>
      <div className="flex justify-between items-center mb-4 sm:mb-6">
        <h2 className="text-base sm:text-lg font-semibold flex items-center">
          <BookOpen size={18} className="mr-2 text-primary" />
          Repository List
        </h2>
        <button
          onClick={handleRefresh}
          disabled={isRefreshing}
          className={`flex items-center gap-1 sm:gap-2 px-3 sm:px-4 py-1.5 sm:py-2 rounded-lg text-xs sm:text-sm border border-border bg-background hover:bg-muted/50 transition-colors ${
            isRefreshing ? "opacity-50 cursor-not-allowed" : ""
          }`}
        >
          <RefreshCw
            size={12}
            className={`text-muted-foreground sm:w-4 sm:h-4 ${isRefreshing ? "animate-spin" : ""}`}
          />
          {isRefreshing ? "Refreshing..." : "Refresh"}
        </button>
      </div>

      <div className="flex flex-col md:flex-row gap-3 sm:gap-4 mb-5 sm:mb-6">
        <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} />

        <div className="flex gap-2">
          <div className="relative" ref={filterDropdownRef}>
            <button
              onClick={() => setIsFilterDropdownOpen(!isFilterDropdownOpen)}
              className="flex items-center gap-1 sm:gap-2 px-3 sm:px-4 py-2.5 sm:py-3 text-xs sm:text-sm bg-background border border-border rounded-xl hover:border-primary/50 transition-colors focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <Filter size={14} className="text-muted-foreground sm:w-4 sm:h-4" />
              <span>
                {filter === "all"
                  ? "All"
                  : filter.charAt(0).toUpperCase() + filter.slice(1).replace(/-/g, " ")}
              </span>
              <ChevronDown
                size={14}
                className={`transition-transform text-muted-foreground sm:w-4 sm:h-4 ${isFilterDropdownOpen ? "rotate-180" : ""}`}
              />
            </button>

            {isFilterDropdownOpen && (
              <div className="absolute z-10 mt-2 w-48 sm:w-52 bg-card rounded-xl shadow-lg overflow-hidden border border-border animate-in fade-in-50 slide-in-from-top-5">
                <div className="py-1">
                  <button
                    onClick={() => {
                      setFilter("all")
                      setIsFilterDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${filter === "all" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {filter === "all" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    All repositories
                  </button>
                </div>
                <div className="border-t border-border py-1">
                  <button
                    onClick={() => {
                      setFilter("active")
                      setIsFilterDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${filter === "active" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {filter === "active" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    Active
                  </button>
                </div>
                <div className="border-t border-border py-1">
                  <button
                    onClick={() => {
                      setFilter("public")
                      setIsFilterDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${filter === "public" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {filter === "public" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    Public
                  </button>
                  <button
                    onClick={() => {
                      setFilter("private")
                      setIsFilterDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${filter === "private" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {filter === "private" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    Private
                  </button>
                </div>
              </div>
            )}
          </div>

          <div className="relative" ref={sortDropdownRef}>
            <button
              onClick={() => setIsSortDropdownOpen(!isSortDropdownOpen)}
              className="flex items-center gap-1 sm:gap-2 px-3 sm:px-4 py-2.5 sm:py-3 text-xs sm:text-sm bg-background border border-border rounded-xl hover:border-primary/50 transition-colors focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <ArrowUpDown size={14} className="text-muted-foreground sm:w-4 sm:h-4" />
              <span>Sort: {getSortLabel(sortBy)}</span>
              <ChevronDown
                size={14}
                className={`transition-transform text-muted-foreground sm:w-4 sm:h-4 ${isSortDropdownOpen ? "rotate-180" : ""}`}
              />
            </button>

            {isSortDropdownOpen && (
              <div className="absolute right-0 z-10 mt-2 w-48 sm:w-52 bg-card rounded-xl shadow-lg overflow-hidden border border-border animate-in fade-in-50 slide-in-from-top-5">
                <div className="py-1">
                  <button
                    onClick={() => {
                      setSortBy("name")
                      setIsSortDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${sortBy === "name" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {sortBy === "name" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    Name
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {searchQuery && (
        <div className="flex items-center mb-4 sm:mb-5 ml-1">
          <span className="text-xs sm:text-sm text-muted-foreground mr-1 sm:mr-2">
            Searching for:
          </span>
          <div className="bg-primary/10 text-primary px-2 sm:px-3 py-1 sm:py-1.5 rounded-full text-xs sm:text-sm flex items-center gap-1 sm:gap-1.5">
            <span>{searchQuery}</span>
            <button
              onClick={() => setSearchQuery("")}
              className="text-primary hover:text-primary/80"
            >
              <X size={12} className="sm:w-4 sm:h-4" />
            </button>
          </div>
        </div>
      )}

      {filteredRepositories.length === 0 ? (
        <div className="text-center py-16 sm:py-20 bg-card/50 rounded-xl border border-dashed border-border">
          <div className="inline-flex items-center justify-center w-16 h-16 sm:w-20 sm:h-20 rounded-full bg-muted/40 mb-3 sm:mb-4">
            <Search size={24} className="text-muted-foreground sm:w-7 sm:h-7" />
          </div>
          <h3 className="text-base sm:text-lg font-medium mb-1 sm:mb-2">No repositories found</h3>
          <p className="text-xs sm:text-sm text-muted-foreground max-w-md mx-auto">
            {
              "We couldn't find any repositories matching your search criteria. Try adjusting your filters or search term."
            }
          </p>
          <button
            onClick={() => {
              setSearchQuery("")
              setFilter("all")
            }}
            className="mt-4 sm:mt-5 px-4 sm:px-5 py-2 sm:py-2.5 bg-primary text-primary-foreground rounded-lg sm:rounded-xl text-xs sm:text-sm hover:bg-primary/90 transition-colors"
          >
            Clear filters
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-5">
          {filteredRepositories.map(repo => (
            <RepositoryCard key={repo.id} repo={repo} />
          ))}
        </div>
      )}
    </>
  )
}
