"use client";

import Image from "next/image";
import React, { useEffect, useState } from "react";
import FilterSection from "./filter-section";
import { CheckIcon } from "@/modules/icons";
import filterService from "@/lib/services/design-templates";
import {
  GetColorResponse,
  GetIndustryResponse,
} from "@/lib/types/models/design-templates";

interface FilterContentProps {
  selectedSize: string;
  onSizeChange: (size: string) => void;
  selectedPaper: string;
  onPaperChange: (paper: string) => void;
  cornerType: string;
  onCornerChange: (corner: string) => void;
  filters: {
    addImage: boolean;
    orientation: string[];
  };
  onFilterChange: (key: string, value: boolean) => void;
  selectedFilters: string[];
  onToggleFilter: (filter: string) => void;
  expandedSections?: string[];
  onToggleSection?: (section: string) => void;
  isMobile?: boolean;
}
export default function Page({
  selectedSize,
  onSizeChange,
  selectedPaper,
  onPaperChange,
  cornerType,
  onCornerChange,
  filters,
  onFilterChange,
  selectedFilters,
  onToggleFilter,
  expandedSections = [],
  onToggleSection = () => { },
  isMobile = false,
}: FilterContentProps) {
  const WrapperProps = (title: string, badge?: number) =>
    isMobile
      ? {
        title,
        badge,
        isCollapsible: true,
        isExpanded: expandedSections.includes(title),
        onToggle: () => onToggleSection(title),
      }
      : {
        title,
        badge,
        showBorder: title !== "Sizes",
      };

  const [industries, setIndustries] = useState<GetIndustryResponse["data"]>([]);
  const [colors, setColors] = useState<GetColorResponse["data"]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [industryRes, colorRes] = await Promise.all([
          filterService.fetchIndustries(),
          filterService.fetchColors(),
        ]);

        setIndustries(industryRes.data);
        setColors(colorRes.data);
      } catch (err) {
        console.error("Error fetching filter data:", err);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      {/* Product Options Section */}
      <FilterSection
        {...WrapperProps("Product Options")}
        showBorder={isMobile ? true : false}
      >
        <div className="space-y-3">
          <select
            className="w-full px-3 py-2 bg-background border border-border rounded text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary"
            value={selectedSize}
            onChange={(e) => onSizeChange(e.target.value)}
          >
            <option value="businesscard_us">Standard</option>
            <option value="businesscard">MOO</option>
            <option value="businesscard_square">Square</option>
            <option value="Mini">Mini</option>
          </select>
          <p className="text-xs text-muted-foreground">
            measures 2.56&quot; x 2.56&quot;
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium text-foreground mb-2 mt-2">
            Paper
          </label>
          <select
            className="w-full px-3 py-2 bg-background border border-border rounded text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary"
            value={selectedPaper}
            onChange={(e) => onPaperChange(e.target.value)}
          >
            <option value="Original">Original</option>
            <option value="cotton">Cotton</option>
            <option value="Super">Super</option>
            <option value="Luxe">Luxe</option>
          </select>
          <p className="text-xs text-muted-foreground mt-1">
            Choose your preferred paper type.
          </p>
        </div>

        <div className="space-y-3 pt-1">
          <label className="block text-sm font-medium text-foreground">
            Corners
          </label>
          <div className="flex">
            {["square", "rounded"].map((type) => (
              <button
                key={type}
                onClick={() => onCornerChange(type)}
                className={`relative flex-1 h-12 border transition-all ${cornerType === type
                  ? "border-b-[3px] border border-b-primary"
                  : "border-border"
                  } ${type === "square" ? "rounded-l-md" : "rounded-r-md"}`}
              >
                <Image
                  src={`https://www.moo.com/static-assets/buildhub/build/img/action-panel-icon-svgs/${type}_corners.svg`}
                  alt={`${type} corners`}
                  width={32}
                  height={16}
                  className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
                />
              </button>
            ))}
          </div>
        </div>
      </FilterSection>

      {/* Layout Section */}
      <FilterSection {...WrapperProps("Layout")}>
        <div className="space-y-4">
          <div>
            <div className="text-xs font-medium text-foreground mb-3">
              Orientation
            </div>
            <div className="space-y-3">
              {["Landscape", "Portrait"].map((label, idx) => (
                <label
                  key={label}
                  className="flex items-center gap-3 cursor-pointer"
                >
                  <input
                    type="checkbox"
                    className="w-4 h-4 rounded border-border bg-white accent-primary cursor-pointer focus:ring-primary"
                  />
                  <span className="text-sm text-foreground">{label}</span>
                  <span className="text-xs text-muted-foreground ml-auto">
                    {idx === 0 ? 190 : 68}
                  </span>
                </label>
              ))}
            </div>
          </div>

          <div>
            <div className="text-xs font-medium text-foreground mb-3">Edit</div>
            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                className="w-4 h-4 rounded border-border bg-white accent-primary cursor-pointer focus:ring-primary"
                checked={filters.addImage}
                onChange={() => onFilterChange("addImage", !filters.addImage)}
              />
              <span className="text-sm text-foreground">Add Image</span>
              <span className="text-xs text-muted-foreground ml-auto">72</span>
            </label>
          </div>
        </div>
      </FilterSection>

      {/* Industry Section */}
      <FilterSection {...WrapperProps("Industry", isMobile ? 2 : undefined)}>
        <div className="space-y-3">
          {industries.map((item) => (
            <label
              key={item._id}
              className={`flex items-center gap-3 cursor-pointer ${item.status === false ? "opacity-50 cursor-not-allowed" : ""
                }`}
            >
              <input
                type="checkbox"
                checked={selectedFilters.includes(item.name)}
                onChange={() => onToggleFilter(item.name)}
                className="w-4 h-4 rounded border-border bg-white accent-primary cursor-pointer focus:ring-primary"
                disabled={item.status === false}
              />
              <span className="text-sm text-foreground flex-1 truncate">
                {item.name}
              </span>
            </label>
          ))}
        </div>
      </FilterSection>

      {/* Color Section */}
      <FilterSection {...WrapperProps("Color")}>
        <div className="space-y-3">
          {/* <p className="text-[15px] text-muted-foreground leading-relaxed"> After you choose a template, you can customize the color of the text or background to create something that&apos;s uniquely yours. </p> */}
          <div className="flex flex-wrap gap-2.5 p-2">
            {colors.map((color) => (
              <label
                key={color._id}
                htmlFor={color.name}
                title={color.name}
                className="cursor-pointer group"
              >
                <input
                  id={color._id}
                  type="checkbox"
                  className="sr-only peer"
                  checked={selectedFilters.includes(color.name)}
                  onChange={() => onToggleFilter(color.name)}
                />
                <span className="flex justify-center items-center size-5.5 rounded-full transition-all duration-200">
                  <span
                    className={`size-4 rounded-full flex items-center justify-center relative transition-all duration-200 ${color.name.toLowerCase() === "white"
                      ? "border border-gray-300"
                      : ""
                      }`}
                    style={{ backgroundColor: color.hexCode }}
                  >
                    {selectedFilters.includes(color.name) && (
                      <CheckIcon
                        stroke={
                          color.name.toLowerCase() === "white"
                            ? "#212121"
                            : "white"
                        }
                      />
                    )}
                  </span>
                </span>
              </label>
            ))}
          </div>
        </div>
      </FilterSection>
    </div>
  );
}
