"use client";

import { useState, useMemo } from "react";
import { Search, Smartphone, Check, X } from "lucide-react";
import { cn } from "@/shared/utils";

// Device categories with their devices
const DEVICE_CATEGORIES = [
  {
    name: "Apple iPhone",
    devices: [
      "iPhone 16 Series (Standard/Plus/Pro/Pro Max)",
      "iPhone 15 Series (Standard/Plus/Pro/Pro Max)",
      "iPhone 14 Series (Standard/Plus/Pro/Pro Max)",
      "iPhone SE (3rd Generation, 2022)",
      "iPhone 13 Series (Standard/Mini/Pro/Pro Max)",
      "iPhone 12 Series (Standard/Mini/Pro/Pro Max)",
      "iPhone SE (2nd Generation, 2020)",
      "iPhone 11 Series (Standard/Pro/Pro Max)",
      "iPhone XS Series (Standard/Max)",
      "iPhone XR",
      "iPhone X (4G Only)",
      "iPhone 8 / 8 Plus (4G Only)",
      "iPhone 7 / 7 Plus (4G Only)",
      "iPhone 6s / 6s Plus (4G Only)",
    ],
  },
  {
    name: "Apple iPad",
    devices: [
      "iPad Pro 13-inch (M4)",
      'iPad Pro 12.9" (6th/5th/4th/3rd Generations)',
      'iPad Pro 11" (4th/3rd/2nd/1st Generations)',
      "iPad Air 13-inch (M2)",
      "iPad Air (5th/4th/3rd Generations)",
      "iPad Mini (6th/5th Generations, A17 Pro)",
      "iPad Standard (10th/9th/8th/7th Generations)",
    ],
  },
  {
    name: "Google Pixel",
    devices: [
      "Pixel 9 Series (Pro XL/Pro/Fold/Standard)",
      "Pixel 8 / 8a / 8 Pro",
      "Pixel 7a / 7 / 7 Pro",
      "Pixel Fold",
      "Pixel 6a / 6 / 6 Pro",
      "Pixel 5a (5G) / 5",
      "Pixel 4a (5G) / 4a",
      "Pixel 4 XL / 4",
      "Pixel 3a XL / 3a",
      "Pixel 3 XL / 3",
    ],
  },
  {
    name: "Samsung Galaxy S Series",
    devices: [
      "Galaxy S25 Edge",
      "Galaxy S24 Ultra / S24 / S24 FE",
      "Galaxy S23 Ultra / S23 / S23 FE",
      "Galaxy S22 Ultra 5G / S22+ 5G / S22 5G",
      "Galaxy S21 Ultra 5G / S21+ 5G / S21 5G",
      "Galaxy S20 Ultra / S20+ 5G / S20+ / S20 5G / S20",
      "Galaxy S10",
      "Galaxy S7 edge / S6 / S6 edge",
      "Galaxy S5 ACTIVE / S5 / S4",
    ],
  },
  {
    name: "Samsung Galaxy Z / Note / A Series",
    devices: [
      "Galaxy Z Fold 6 / 5 / 4 / 3 / 2",
      "Galaxy Z Flip 6 / 5 / 4 / 3 5G",
      "Galaxy Note 20 Ultra 5G / Note 20 5G",
      "Galaxy A56 5G / A55 5G / A54 5G / A53 5G",
      "Galaxy A52s 5G / A51 5G / A35 5G / A23 5G",
      "Galaxy M23 5G",
    ],
  },
  {
    name: "Sony Xperia",
    devices: [
      "Xperia 1 VI / 1 V / 1 IV / 1 III / 1 II",
      "Xperia 5 V / 5 IV / 5 III / 5 II",
      "Xperia 10 VI / 10 V / 10 IV / 10 III Lite",
      "Xperia Pro-I / Pro",
      "Xperia Ace III / Ace II / Ace",
      "Xperia 8 Lite / XZ Premium",
      "Xperia X Performance / Z5 Premium / Z5 Compact / Z5",
      "Xperia Z4 / Z3 Compact / Z2 / Z",
    ],
  },
  {
    name: "Sharp AQUOS",
    devices: ["AQUOS R9 / R8 / R7", "AQUOS sense9 / sense8 / sense7", "AQUOS wish4 / wish3"],
  },
  {
    name: "Xiaomi / Redmi",
    devices: [
      "Xiaomi 14T Pro / 14T / 14 Ultra / 14 Pro / 14 Pro+",
      "Xiaomi 13T Pro / 13T / 13 Pro / 13 / 13 Lite",
      "Xiaomi 12T Pro",
      "Redmi Note 14 Pro / 13 Pro+ / 13 Pro 5G",
      "Redmi Note 11 Pro 5G / 10T",
      "Redmi 12 5G",
    ],
  },
  {
    name: "Motorola",
    devices: [
      "Edge 50 Ultra / 50s Pro / 50 Pro / 50 Neo / 50 Fusion",
      "Edge 40 Pro / 40 Neo / 40",
      "Edge+ (2024) / Edge+ (2023)",
      "Razr 50 Ultra / 50 / 40 Ultra / 40",
      "Razr 2024 / 2022 / 5G / 2019",
      "Moto G85 / G64y 5G / G55 / G54 / G35",
      "Moto G53J 5G / G52J 5G",
      "ThinkPhone 25",
    ],
  },
  {
    name: "OPPO / OnePlus",
    devices: [
      "OPPO Find X8 / X5 Pro / X5 / X3 Pro",
      "OPPO Find N2 Flip",
      "OPPO Reno11 A / 10 Pro 5G / 9 A / 7 A",
      "OPPO Reno6 Pro 5G / Reno 5 A / Reno A",
      "OPPO A79 5G / A73 / A55s 5G / A3 5G",
      "OnePlus 13 / 12 / 11",
    ],
  },
  {
    name: "ASUS",
    devices: [
      "Zenfone 9 / 8 Flip / 8",
      "ROG Phone 7 / 6 / 5 / 3 / II",
      "ZenFone 7 Pro / 7 / 6",
      "ZenFone 5Z / 5 / 5Q",
      "ZenFone 4 Series / 3 Series",
      "ZenFone Max Series",
    ],
  },
  {
    name: "Vivo / Nokia",
    devices: ["Vivo X100 Pro / X90 Pro", "Vivo V40 / V29 / V29 Lite 5G", "Nokia XR21 / X30 / G60"],
  },
  {
    name: "HUAWEI",
    devices: [
      "P40 Pro 5G / P40 / P40 lite 5G / P40 lite E",
      "Mate 40 Pro+ / Mate 40 Pro / Mate 40",
      "Mate 20 Pro / Mate 20 lite / Mate 10 Pro",
      "P30 / P30 lite / P20 / P20 lite",
      "nova 5T / nova lite 3+ / nova lite 3 / nova 3",
      "MediaPad M5 / M3 / T5 Series",
    ],
  },
  {
    name: "Fujitsu arrows",
    devices: [
      "arrows We2 Plus / We2 / N",
      "arrows NX9 F-52A",
      "arrows M05 / M04 / M03 / M02",
      "arrows SV F-03H / NX F-02H",
    ],
  },
  {
    name: "Other Devices",
    devices: [
      "DuraForce EX KY-51D / PRO",
      "Kids Phones (Compact/KY-41C/SH-03M)",
      "ASUS Chromebook CM30 Detachable",
      "dtab Compact (d-52C/d-42A) / Standard (d-51C)",
      "Essential Phone PH-1",
      "HTC U12+ / U11 / U11 life",
      "CAT S60 / S41 / S40",
      "BlackBerry PRIV / Passport / Classic",
      "Microsoft Surface Pro LTE / Surface 3 (4G)",
      "Lenovo Tab4 8 / YOGA Series",
      "LG Nexus 5X / Nexus 5",
    ],
  },
];

// Flatten all devices for search
const ALL_DEVICES = DEVICE_CATEGORIES.flatMap(category =>
  category.devices.map(device => ({
    device,
    category: category.name,
  }))
);

function DeviceSearchResults({
  filteredDevices,
  showNoResults,
}: {
  filteredDevices: { device: string; category: string }[];
  showNoResults: boolean;
}) {
  if (filteredDevices.length > 0) {
    return (
      <div className="divide-y divide-border">
        {filteredDevices.map((item, index) => (
          <div
            key={index}
            className="flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors"
          >
            <div className="flex-shrink-0 h-8 w-8 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
              <Check className="h-4 w-4 text-green-600 dark:text-green-400" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="font-medium text-foreground truncate">{item.device}</p>
              <p className="text-xs text-muted-foreground">{item.category}</p>
            </div>
            <span className="text-xs font-medium text-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/30 px-2 py-1 rounded-full">
              Compatible
            </span>
          </div>
        ))}
        {filteredDevices.length === 20 && (
          <p className="text-xs text-muted-foreground text-center py-2">
            Showing first 20 results. Try a more specific search.
          </p>
        )}
      </div>
    );
  }

  if (showNoResults) {
    return (
      <div className="p-6 text-center">
        <div className="flex-shrink-0 h-12 w-12 mx-auto rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center mb-3">
          <X className="h-6 w-6 text-amber-600 dark:text-amber-400" />
        </div>
        <p className="font-medium text-foreground mb-1">Device not found in our list</p>
        <p className="text-sm text-muted-foreground">
          Your device may still be compatible. Please{" "}
          <a href="mailto:info@asolutions.co.jp" className="text-primary hover:underline">
            contact us
          </a>{" "}
          to verify compatibility.
        </p>
      </div>
    );
  }

  return null;
}

export function DeviceCompatibility() {
  const [searchQuery, setSearchQuery] = useState("");
  const [isExpanded, setIsExpanded] = useState(false);

  const filteredDevices = useMemo(() => {
    if (!searchQuery.trim()) return [];

    const query = searchQuery.toLowerCase();
    return ALL_DEVICES.filter(
      item =>
        item.device.toLowerCase().includes(query) || item.category.toLowerCase().includes(query)
    ).slice(0, 20);
  }, [searchQuery]);

  const hasResults = filteredDevices.length > 0;
  const showNoResults = searchQuery.trim().length > 0 && !hasResults;

  return (
    <section className="mt-12 mb-8">
      <h2 className="text-2xl font-bold text-foreground mb-2 text-center">Device Compatibility</h2>
      <p className="text-sm text-muted-foreground text-center mb-6">
        Check if your device is compatible with our SIM service
      </p>

      <div className="max-w-xl mx-auto mb-6">
        <div className="relative">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
          <input
            type="text"
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            placeholder="Search your device (e.g., iPhone 15, Galaxy S24, Pixel 8)"
            className="w-full pl-12 pr-4 py-3 rounded-xl border border-border bg-card text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
          />
        </div>

        {searchQuery.trim() && (
          <div className="mt-3 rounded-xl border border-border bg-card overflow-hidden">
            <DeviceSearchResults filteredDevices={filteredDevices} showNoResults={showNoResults} />
          </div>
        )}
      </div>

      <div className="max-w-3xl mx-auto">
        <button
          type="button"
          onClick={() => setIsExpanded(!isExpanded)}
          className="w-full flex items-center justify-center gap-2 py-3 text-sm font-medium text-primary hover:text-primary/80 transition-colors"
        >
          <Smartphone className="h-4 w-4" />
          {isExpanded ? "Hide full device list" : "View all compatible devices"}
        </button>

        {isExpanded && (
          <div className="mt-4 rounded-xl border border-border bg-card overflow-hidden">
            <div className="p-4 bg-muted/30 border-b border-border">
              <p className="text-sm text-muted-foreground">
                Below is a comprehensive list of devices confirmed to work with our SIM service.
                Devices not listed may still be compatible.
              </p>
            </div>
            <div className="divide-y divide-border">
              {DEVICE_CATEGORIES.map((category, catIndex) => (
                <DeviceCategorySection key={catIndex} category={category} />
              ))}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

function DeviceCategorySection({ category }: { category: (typeof DEVICE_CATEGORIES)[number] }) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full flex items-center justify-between gap-3 p-4 text-left hover:bg-muted/50 transition-colors"
      >
        <span className="font-medium text-foreground">{category.name}</span>
        <span
          className={cn(
            "text-xs text-muted-foreground transition-transform",
            isOpen && "rotate-180"
          )}
        >
          ▼
        </span>
      </button>
      {isOpen && (
        <div className="px-4 pb-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            {category.devices.map((device, index) => (
              <div key={index} className="flex items-center gap-2 text-sm text-muted-foreground">
                <Check className="h-3.5 w-3.5 text-green-500 flex-shrink-0" />
                <span>{device}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

export default DeviceCompatibility;
