"use client";

import { useState } from "react";
import { ArrowUpRight, Clock3, FileSearch, Search, Settings2, ShieldCheck, SlidersHorizontal, Zap } from "lucide-react";
import { Input } from "@/components/ui/input";
import { EmptyState } from "@/components/shared/panel";
import type { Chargepoint } from "../types";
import { operations, type OperationGroup, type OperationCommand } from "./catalog.ts";
import { CommandDialog } from "./command-dialog";
import { SecurityWorkflowDialog } from "./security-workflow-dialog";

const groups = [
  { name: "Device", icon: Settings2, description: "Read settings, apply changes, and request device updates." },
  { name: "Diagnostics", icon: FileSearch, description: "Collect the information needed to investigate a charger." },
  { name: "Security", icon: ShieldCheck, description: "Manage authorization data, credentials, and certificates." },
  { name: "Charging", icon: Zap, description: "Operate connectors and manage charging controls." },
] satisfies { name: OperationGroup; icon: typeof Settings2; description: string }[];
const availableCount = operations.filter(operation => operation.command).length;

export function ConfigView({ chargepoint, source }: { chargepoint: Chargepoint; source: "api" | "preview" }) {
  const [search, setSearch] = useState("");
  const [command, setCommand] = useState<OperationCommand>();
  const query = search.trim().toLowerCase();
  const matching = operations.filter(operation => `${operation.title} ${operation.description} ${operation.group}`.toLowerCase().includes(query));
  return (
    <section className="flex flex-col gap-6" aria-labelledby="remote-operations-title">
      <div className="panel flex flex-wrap items-center justify-between gap-4 p-5 md:p-6">
        <div className="flex items-start gap-3">
          <span className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">
            <SlidersHorizontal aria-hidden="true" className="size-5" />
          </span>
          <div>
            <div className="flex flex-wrap items-center gap-2">
              <h2 id="remote-operations-title" className="text-lg font-semibold">Remote operations</h2>
              <span className="rounded-full bg-primary/10 px-2.5 py-1 text-xs font-medium text-primary">{availableCount} available</span>
            </div>
            <p className="mt-1 text-sm text-muted-foreground">Choose an operation to configure a request for this chargepoint.</p>
          </div>
        </div>
        <div className="relative w-full sm:w-64">
          <Search aria-hidden="true" className="pointer-events-none absolute left-3 top-3.5 size-4 text-muted-foreground" />
          <Input aria-label="Search operations" placeholder="Search operations…" value={search} onChange={event => setSearch(event.target.value)} className="pl-9" />
        </div>
      </div>
      {groups.map(group => {
        const items = matching.filter(operation => operation.group === group.name);
        if (!items.length) return null;
        const Icon = group.icon;
        return (
          <section key={group.name} aria-labelledby={`operation-group-${group.name}`} className="flex flex-col gap-3">
            <div className="flex items-center gap-3">
              <Icon aria-hidden="true" className="size-5 text-muted-foreground" />
              <div>
                <h3 id={`operation-group-${group.name}`} className="font-semibold">{group.name}</h3>
                <p className="mt-0.5 text-sm text-muted-foreground">{group.description}</p>
              </div>
            </div>
            <ul className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {items.map(operation => (
                <li key={operation.id}>
                  <button
                    type="button" disabled={!operation.command}
                    onClick={() => { if (operation.command) setCommand(operation.command); }}
                    className="group flex h-full w-full items-start gap-3 rounded-xl border border-border bg-card p-4 text-left transition-colors enabled:hover:border-primary/50 enabled:hover:bg-primary/5 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:bg-muted/20"
                  >
                    <span className="min-w-0 flex-1">
                      <span className="block font-medium leading-snug">{operation.title}</span>
                      <span className="mt-1.5 block text-sm leading-relaxed text-muted-foreground">{operation.description}</span>
                      {!operation.command && (
                        <span className="mt-3 inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground">
                          <Clock3 aria-hidden="true" className="size-3" />Not available yet
                        </span>
                      )}
                    </span>
                    {operation.command && <ArrowUpRight aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-primary" />}
                  </button>
                </li>
              ))}
            </ul>
          </section>
        );
      })}
      {!matching.length && <EmptyState title="No matching operations" description="Try a different operation name or category." />}
      {command && (command === "certificate-signed" || command === "upgrade-security-profile"
        ? <SecurityWorkflowDialog key={command} workflow={command} chargepoint={chargepoint} source={source} onClose={() => setCommand(undefined)} />
        : <CommandDialog key={command} command={command} chargepoint={chargepoint} source={source} onClose={() => setCommand(undefined)} />)}
    </section>
  );
}
