"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Layers, Loader2 } from "lucide-react";

import { ServiceOption } from "../../task/type/task.type";
import { useGetAvailableServices } from "../../task/hook/task.hook";
import { Skeleton } from "@/components/ui/skeleton";


export function ServiceGrid() {
  const router = useRouter();
  const { data: servicesRes, isLoading: loadingServices } = useGetAvailableServices();
  const [browseCategory, setBrowseCategory] = useState("ALL");

  const services = useMemo(() => servicesRes?.data ?? [], [servicesRes]);
  const categories = useMemo(() => Array.from(new Set(services.map((s) => s.category))), [services]);
  
 const [navigatingTo, setNavigatingTo] = useState<string | null>(null);

const handleApplyService = (svc: ServiceOption) => {
  setNavigatingTo(svc.id);

   const params = new URLSearchParams({
      serviceId: svc.id,
      title: svc.name,
      category: svc.category,
    });
    router.push(`/client/tasks/create?${params.toString()}`);
};
  const visibleServices =
    browseCategory === "ALL" ? services : services.filter((s) => s.category === browseCategory);

  // const handleApplyService = (svc: ServiceOption) => {
    // const params = new URLSearchParams({
    //   serviceId: svc.id,
    //   title: svc.name,
    //   category: svc.category,
    // });
    // router.push(`/client/tasks/create?${params.toString()}`);
  // };

  return (
    <div className="space-y-4">
      <Card className="border-border bg-card shadow-sm">
        <CardHeader className="py-4 px-5">
          <h2 className="text-2xl font-bold tracking-tight text-foreground">Services</h2>
          <p className="text-muted-foreground text-sm mt-1">Choose a service</p>
        </CardHeader>
      </Card>

      {/* Category filter chips */}
      <div className="flex flex-wrap gap-2">
        <button
          onClick={() => setBrowseCategory("ALL")}
          className={`text-xs font-semibold px-3 py-1.5 rounded-full border transition-colors ${
            browseCategory === "ALL"
              ? "bg-primary text-primary-foreground border-primary"
              : "bg-background text-muted-foreground border-border hover:bg-muted"
          }`}
        >
          All Services
        </button>
        {categories.map((cat) => (
          <button
            key={cat}
            onClick={() => setBrowseCategory(cat)}
            className={`text-xs font-semibold px-3 py-1.5 rounded-full border transition-colors ${
              browseCategory === cat
                ? "bg-primary text-primary-foreground border-primary"
                : "bg-background text-muted-foreground border-border hover:bg-muted"
            }`}
          >
            {cat}
          </button>
        ))}
      </div>

      {loadingServices ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
    {Array.from({ length: 6 }).map((_, i) => (
      <Card key={`skeleton-${i}`} className="flex flex-col justify-between">
        <CardContent className="p-4 flex flex-col gap-3 h-full">
          <div className="flex items-start justify-between gap-2">
            <Skeleton className="h-4 w-2/3" />
            <Skeleton className="h-4 w-12 rounded-full" />
          </div>
          <Skeleton className="h-3 w-full" />
          <Skeleton className="h-3 w-4/5 -mt-1" />
          <div className="flex items-center justify-between mt-auto pt-1">
            <Skeleton className="h-5 w-16" />
            <Skeleton className="h-8 w-16 rounded-md" />
          </div>
        </CardContent>
      </Card>
    ))}
  </div>
      ) : visibleServices.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-center gap-2 border rounded-xl">
          <Layers className="h-8 w-8 text-muted-foreground/50" />
          <p className="text-sm font-semibold text-muted-foreground">No services found</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {visibleServices.map((svc) => (
            <Card key={svc.id} className="flex flex-col justify-between hover:shadow-sm transition-shadow">
              <CardContent className="p-4 flex flex-col gap-3 h-full">
                <div className="flex items-start justify-between gap-2">
                  <p className="text-sm font-semibold leading-snug">{svc.name}</p>
                  <Badge variant="secondary" className="text-[10px] shrink-0">{svc.category}</Badge>
                </div>

                {(svc as any).description && (
                  <p className="text-xs text-muted-foreground -mt-2 line-clamp-2">
                    {(svc as any).description}
                  </p>
                )}

                <div className="flex items-center justify-between mt-auto pt-1">
                  <span className="text-base font-bold text-primary">
                    {(svc as any).price ? `₹${(svc as any).price}` : "—"}
                  </span>
                  {/* <Button size="sm" onClick={() => handleApplyService(svc)}>
                    Apply
                  </Button> */}

                  <Button
                    size="sm"
                    onClick={() => handleApplyService(svc)}
                    disabled={navigatingTo === svc.id}
                  >
                    {navigatingTo === svc.id && (
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    )}
                    {navigatingTo === svc.id ? "Apply..." : "Apply"}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}