"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useProductBySku } from "@/app/_features/products/useProducts";
import { updateCount } from "@/app/_services/apiProducts";
import { formatAxiosError } from "@/app/lib/utils";
import { SkeletonProductForSku } from "@/app/components/skeletons/SkeletonProduct";
import { Card, CardContent } from "@/app/components/ui/card";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/app/components/ui/select";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/app/components/ui/carousel";
import {
  Phone,
  Mail,
  Globe,
  Search,
  MapPin,
  LocateFixed,
  Building2,
} from "lucide-react";
import { motion } from "framer-motion";

const ProductDetails = ({ sku }) => {
  const { isLoading, isError, error, data } = useProductBySku(sku);

  const [hideNoStock, setHideNoStock] = useState(true);
  const [address, setAddress] = useState("");
  const [postalCode, setPostalCode] = useState("");
  const [searchRange, setSearchRange] = useState("30");
  const [isSearching, setIsSearching] = useState(false);
  const [isLocating, setIsLocating] = useState(false);
  const [searchResults, setSearchResults] = useState(null);

  if (isLoading) return <SkeletonProductForSku />;
  if (isError)
    return <p className="text-destructive">{formatAxiosError(error)}</p>;

  const product = data?.data;

  if (!product)
    return (
      <p className="text-muted-foreground">
        There is no product with that SKU!
      </p>
    );

  const filteredDealers = hideNoStock
    ? product.dealers?.filter((dealer) => dealer.products?.[0]?.stock > 0)
    : product.dealers;

  async function handleClick(dealerId) {
    await updateCount({ dealerId, sku: product?.sku });
  }

  const handleSearch = async () => {
    if (!address.trim() && !postalCode.trim()) {
      alert("Please enter an address or postal code");
      return;
    }

    setIsSearching(true);
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_BASE_URL}/find/dealer/by-address`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            product_id: product?.id,
            distance: searchRange,
            address: address,
            hide_no_stock: hideNoStock,
          }),
        }
      );

      if (!response.ok) {
        throw new Error("Search failed");
      }

      const result = await response.json();
      setSearchResults(result?.data || []);
    } catch (error) {
      console.error("Search error:", error);
      alert(error.message || "Search failed. Please try again.");
      setSearchResults([]);
    } finally {
      setIsSearching(false);
    }
  };

  const handleLocate = () => {
    if (!navigator.geolocation) {
      alert("Geolocation is not supported by your browser.");
      return;
    }

    setIsLocating(true);
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        const { latitude, longitude } = position.coords;
        try {
          const response = await fetch(
            `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}`
          );
          const data = await response.json();
          if (data.status !== "OK" || !data.results[0]) {
            throw new Error("Reverse geocoding failed");
          }
          const addr = data.results[0].formatted_address;
          const components = data.results[0].address_components;
          const postal =
            components.find((comp) => comp.types.includes("postal_code"))
              ?.long_name || "";
          setAddress(addr);
          setPostalCode(postal);
        } catch (error) {
          console.error("Reverse geocoding error:", error);
          alert(
            "Failed to get location. Please enter address or postal code manually."
          );
        } finally {
          setIsLocating(false);
        }
      },
      (error) => {
        console.error("Geolocation error:", error);
        alert(
          "Failed to get location. Please allow location access or enter manually."
        );
        setIsLocating(false);
      }
    );
  };

  const clearSearch = () => {
    setSearchResults(null);
    setAddress("");
    setPostalCode("");
  };

  return (
    <div className="w-full max-w-7xl mx-auto bg-gray-100 rounded-sm p-4 sm:p-6 md:p-8 space-y-6 md:space-y-8">
      <motion.div
        className="grid grid-cols-1 md:grid-cols-12 gap-4 md:gap-6 lg:gap-8"
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.6 }}
      >
        {/* Product Card */}
        <div className="md:col-span-5 lg:col-span-4">
          <Card className="overflow-hidden bg-card border-border shadow-lg hover:shadow-xl transition-shadow duration-300">
            <CardContent className="p-4 sm:p-6 md:p-8">
              <div className="space-y-4 md:space-y-6">
                {product?.images?.[0] && (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ duration: 0.5 }}
                    className="relative overflow-hidden rounded-xl bg-muted"
                  >
                    <Image
                      height={400}
                      width={400}
                      src={product?.images[0]?.image_path || "/placeholder.svg"}
                      alt={product?.name}
                      className="w-full h-48 sm:h-56 md:h-64 object-contain p-4"
                    />
                  </motion.div>
                )}

                <motion.div
                  initial={{ opacity: 0, y: -20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: 0.2 }}
                >
                  <h1 className="text-lg sm:text-xl md:text-2xl font-bold text-foreground leading-tight text-balance">
                    {product?.name}
                  </h1>
                </motion.div>

                <motion.div
                  className="bg-muted/50 p-4 sm:p-6 rounded-xl border border-border"
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: 0.3 }}
                >
                  <div className="flex items-center gap-2 mb-3 sm:mb-4">
                    <MapPin className="w-4 h-4 sm:w-5 sm:h-5 text-primary" />
                    <h3 className="text-base sm:text-lg font-semibold text-foreground">
                      Find Nearby Partner Store
                    </h3>
                  </div>

                  <div className="space-y-3 sm:space-y-4">
                    <div className="flex items-center gap-2 sm:gap-3">
                      <Input
                        placeholder="Enter your address"
                        value={address}
                        onChange={(e) => setAddress(e.target.value)}
                        className="flex-1 bg-background border-border text-sm sm:text-base"
                      />
                      <Button
                        variant="outline"
                        size="icon"
                        onClick={handleLocate}
                        disabled={isLocating}
                        className="shrink-0 bg-transparent h-9 w-9 sm:h-10 sm:w-10"
                      >
                        {isLocating ? (
                          <div className="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                        ) : (
                          <LocateFixed className="w-4 h-4" />
                        )}
                      </Button>
                    </div>

                    <div className="flex flex-col sm:flex-row items-center gap-2 sm:gap-3">
                      <Select
                        value={searchRange}
                        onValueChange={setSearchRange}
                      >
                        <SelectTrigger className="flex-1 bg-background border-border text-sm sm:text-base">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="10">10 km</SelectItem>
                          <SelectItem value="20">20 km</SelectItem>
                          <SelectItem value="30">30 km</SelectItem>
                          <SelectItem value="50">50 km</SelectItem>
                          <SelectItem value="100">100 km</SelectItem>
                          <SelectItem value="200">200 km</SelectItem>
                          <SelectItem value="500">500 km</SelectItem>
                          <SelectItem value="1000">1000 km</SelectItem>
                        </SelectContent>
                      </Select>

                      <Button
                        onClick={handleSearch}
                        disabled={isSearching || isLocating}
                        className="bg-primary hover:bg-primary/90 text-primary-foreground px-4 sm:px-6 text-sm sm:text-base w-full sm:w-auto"
                      >
                        {isSearching ? (
                          <>
                            <Search className="w-4 h-4 mr-2" />
                            Searching...
                          </>
                        ) : (
                          <>
                            <Search className="w-4 h-4 mr-2" />
                            Search
                          </>
                        )}
                      </Button>
                    </div>
                  </div>
                </motion.div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Dealers Section */}
        <div className="md:col-span-7 lg:col-span-8 space-y-4 md:space-y-6">
          <motion.div
            className="flex flex-col sm:flex-row items-start sm:items-center justify-between pb-3 sm:pb-4 border-b border-border"
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <div>
              <h2 className="text-xl sm:text-2xl md:text-3xl font-bold text-foreground">
                {searchResults ? "Search Results" : "Available Dealers"}
              </h2>
              <p className="text-muted-foreground mt-1 text-sm sm:text-base">
                {searchResults
                  ? `Found ${searchResults.length} dealers within ${searchRange} km`
                  : `${filteredDealers?.length || 0} dealers available`}
              </p>
            </div>

            <div className="flex items-center gap-2 sm:gap-3 mt-2 sm:mt-0">
              <Checkbox
                id="hideNoStock"
                checked={hideNoStock}
                onCheckedChange={setHideNoStock}
              />
              <label
                htmlFor="hideNoStock"
                className="text-sm font-medium text-foreground cursor-pointer"
              >
                Show All
              </label>
            </div>
          </motion.div>

          {(searchResults || filteredDealers)?.length === 0 ? (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5 }}
              className="text-center py-8 sm:py-12"
            >
              <div className="max-w-md mx-auto">
                <Building2 className="w-12 h-12 sm:w-16 sm:h-16 text-muted-foreground mx-auto mb-4" />
                <h3 className="text-lg sm:text-xl font-semibold text-foreground mb-2">
                  No dealers found
                </h3>
                <p className="text-muted-foreground mb-4 sm:mb-6 text-sm sm:text-base">
                  No dealers found within {searchRange} km of{" "}
                  {address || postalCode}. Try expanding your search range or
                  check all dealers.
                </p>
                {searchResults && (
                  <Button
                    onClick={clearSearch}
                    variant="outline"
                    className="px-4 sm:px-6 bg-transparent text-sm sm:text-base"
                  >
                    Show All Dealers
                  </Button>
                )}
              </div>
            </motion.div>
          ) : (
            <>
              {searchResults && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5 }}
                  className="flex justify-center sm:justify-end"
                >
                  <Button
                    onClick={clearSearch}
                    variant="outline"
                    className="px-4 sm:px-6 bg-transparent text-sm sm:text-base"
                  >
                    Show All Dealers
                  </Button>
                </motion.div>
              )}
              <Carousel
                className="w-full"
                opts={{
                  align: "start",
                  loop: false,
                }}
              >
                <CarouselContent className="-ml-2 sm:-ml-4">
                  {(searchResults || filteredDealers).map((dealer, index) => (
                    <CarouselItem
                      className="pl-4 md:basis-1/2 lg:basis-1/2 xl:basis-1/3"
                      key={dealer.id}
                    >
                      <DealerCard
                        dealer={dealer}
                        handleClick={handleClick}
                        index={index}
                      />
                    </CarouselItem>
                  ))}
                </CarouselContent>
                <CarouselPrevious className="left-0 hidden sm:flex" />
                <CarouselNext className="right-0 hidden sm:flex" />
              </Carousel>
            </>
          )}
        </div>
      </motion.div>
    </div>
  );
};

const DealerCard = ({ dealer, handleClick, index }) => {
  const hasStock = dealer?.products
    ? dealer.products?.[0]?.stock > 0
    : dealer?.stock;

  return (
    <motion.div
      initial={{ opacity: 0, y: 50 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5, delay: index * 0.1 }}
      className="h-full"
    >
      <Card className="h-[400px] sm:h-[420px] bg-card border-border shadow-md hover:shadow-xl transition-all duration-300 hover:-translate-y-1 flex flex-col">
        <CardContent className="p-4 sm:p-6 flex flex-col h-full">
          {/* Header Section */}
          <div className="flex justify-between items-start mb-3 sm:mb-4">
            <div className="flex-1 min-w-0">
              <h3 className="text-base sm:text-lg font-bold text-foreground truncate mb-1">
                {dealer?.company_name || "Unknown Company"}
              </h3>
              <Badge
                variant={hasStock ? "default" : "destructive"}
                className={`font-medium text-xs sm:text-sm ${
                  hasStock
                    ? "bg-primary text-primary-foreground"
                    : "bg-destructive text-destructive-foreground"
                }`}
              >
                {hasStock ? "In Stock" : "Not Stocked"}
              </Badge>
            </div>
          </div>

          {/* Address Section - Fixed height container */}
          <div className="flex-1 mb-3 sm:mb-4 min-h-[100px] sm:min-h-[120px]">
            <div className="bg-muted/30 p-3 sm:p-4 rounded-lg border border-border h-full overflow-y-auto">
              <h4 className="text-sm font-semibold text-foreground mb-2 flex items-center gap-2">
                <MapPin className="w-4 h-4 text-primary" />
                Address
              </h4>
              <div className="space-y-1 text-xs sm:text-sm text-muted-foreground">
                {dealer?.address_line && (
                  <p className="leading-relaxed">{dealer.address_line}</p>
                )}
                {dealer?.address_line1 && (
                  <p className="leading-relaxed">{dealer.address_line1}</p>
                )}
                {dealer?.street_address && (
                  <p className="leading-relaxed">{dealer.street_address}</p>
                )}
                <div className="flex flex-wrap gap-2 text-xs">
                  {dealer?.city && (
                    <span className="font-medium">{dealer.city}</span>
                  )}
                  {dealer?.state && <span>{dealer.state}</span>}
                  {dealer?.postal_code && <span>{dealer.postal_code}</span>}
                </div>
                {dealer?.country && (
                  <p className="text-xs font-medium text-primary">
                    {dealer.country}
                  </p>
                )}
              </div>
            </div>
          </div>

          {/* Contact Actions - Fixed at bottom */}
          <div className="space-y-2 mt-auto">
            {dealer.phone_number && (
              <Button
                variant="outline"
                size="sm"
                className="w-full justify-start hover:bg-primary hover:text-primary-foreground transition-colors bg-transparent text-xs sm:text-sm"
                asChild
              >
                <Link
                  href={`tel:${dealer.phone_number}`}
                  onClick={() => handleClick(dealer.id)}
                >
                  <Phone className="w-4 h-4 mr-2" />
                  <span className="truncate">{dealer.phone_number}</span>
                </Link>
              </Button>
            )}

            {dealer.email && (
              <Button
                variant="outline"
                size="sm"
                className="w-full justify-start hover:bg-primary hover:text-primary-foreground transition-colors bg-transparent text-xs sm:text-sm"
                asChild
              >
                <Link
                  href={`mailto:${dealer.email}`}
                  onClick={() => handleClick(dealer.id)}
                >
                  <Mail className="w-4 h-4 mr-2" />
                  <span className="truncate">{dealer.email}</span>
                </Link>
              </Button>
            )}

            {dealer.weburl && (
              <Button
                variant="outline"
                size="sm"
                className="w-full justify-start hover:bg-secondary hover:text-secondary-foreground transition-colors bg-transparent text-xs sm:text-sm"
                asChild
              >
                <Link
                  href={dealer.weburl}
                  target="_blank"
                  onClick={() => handleClick(dealer.id)}
                >
                  <Globe className="w-4 h-4 mr-2" />
                  <span className="truncate">Visit Website</span>
                </Link>
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
};

export default ProductDetails;
