"use client";
import { useState } from "react";
import { Plus, Trash, Search, RefreshCw } from "lucide-react";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Panel, EmptyState } from "@/components/shared/panel";
import type { Authorization } from "./types";
export function AuthorizationPanel({ users }: { users: Authorization[] }) {
  const [pending, setPending] = useState<boolean | null>(null);
  const [userSearch, setUserSearch] = useState("");
  const [selectedUser, setSelectedUser] = useState<Authorization>();
  const [notice, setNotice] = useState("");
  const [enabled, setEnabled] = useState(true);
  const [rows, setRows] = useState<Authorization[]>([]);
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  return (
    <div className="space-y-6">
      <Panel
        title="Authorization Settings"
        description="Enable or disable the authorization feature for this chargepoint"
        actions={
          <label className="flex items-center gap-3">
            Authorization Feature
            <Switch
              checked={enabled}
              onCheckedChange={setPending}
              aria-label="Authorization feature"
            />
          </label>
        }
      >
        <span className="sr-only">{enabled ? "Enabled" : "Disabled"}</span>
      </Panel>
      <section className="panel overflow-hidden">
        <div className="flex flex-wrap items-center justify-between gap-4 p-5">
          <div>
            <h2 className="text-xl font-semibold">Authorizations</h2>
            <p className="mt-1 text-muted-foreground">
              Manage user authorizations for this chargepoint
            </p>
          </div>
          <div className="flex w-full flex-wrap gap-2 sm:w-auto">
            <div className="relative min-w-0 flex-1">
              <Input
                aria-label="Search authorizations"
                placeholder="Search authorizations..."
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                className="pr-10"
              />
              <Search className="absolute right-3 top-3 size-5 text-muted-foreground" />
            </div>
            <Button
              variant="outline"
              size="icon"
              aria-label="Refresh authorizations"
              onClick={() => setNotice("Mock authorizations refreshed.")}
            >
              <RefreshCw />
            </Button>
            <Button
              disabled={!enabled}
              onClick={() => {
                if (enabled) setOpen(true);
              }}
            >
              <Plus />
              Add Authorization
            </Button>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="data-table min-w-[700px]">
            <thead>
              <tr>
                {[
                  "Name",
                  "Email",
                  "Phone",
                  "Role",
                  "Created At",
                  "Actions",
                ].map((label) => (
                  <th key={label}>{label}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows
                .filter((row) =>
                  `${row.name} ${row.email}`
                    .toLowerCase()
                    .includes(query.toLowerCase()),
                )
                .map((row) => (
                  <tr key={row.id}>
                    <td>{row.name}</td>
                    <td>{row.email}</td>
                    <td>{row.phone}</td>
                    <td>{row.role}</td>
                    <td>
                      {new Date(row.createdAt).toLocaleDateString("en-US", {
                        timeZone: "Asia/Jakarta",
                      })}
                    </td>
                    <td>
                      <Button
                        variant="ghost"
                        size="icon-sm"
                        aria-label={`Remove authorization for ${row.name}`}
                        disabled={!enabled}
                        onClick={() => {
                          if (enabled)
                            setRows((current) =>
                              current.filter((item) => item.id !== row.id),
                            );
                        }}
                      >
                        <Trash />
                      </Button>
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
          {!rows.filter((row) =>
            `${row.name} ${row.email}`
              .toLowerCase()
              .includes(query.toLowerCase()),
          ).length && (
            <EmptyState
              title="No authorizations found"
              description="Try adjusting your search criteria"
            />
          )}
        </div>
      </section>
      {notice && (
        <p role="status" className="text-muted-foreground">
          {notice}
        </p>
      )}
      <Dialog
        open={pending !== null}
        onOpenChange={(open) => {
          if (!open) setPending(null);
        }}
      >
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>
              {pending ? "Enable" : "Disable"} Authorization Feature?
            </DialogTitle>
            <DialogDescription>
              You are about to {pending ? "enable" : "disable"} the
              authorization feature for this chargepoint.
            </DialogDescription>
          </DialogHeader>
          <div className="rounded-lg border border-warning/30 bg-warning/10 p-4 text-warning">
            <p className="mb-2 font-semibold">Important Notice:</p>
            <p>
              By {pending ? "enabling" : "disabling"} this feature, you are
              responsible for ensuring proper access control when{" "}
              {pending ? "managing" : "granting"} user authorizations. This
              action will {pending ? "allow" : "prevent"} authorization
              management for this chargepoint.
            </p>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setPending(null)}>
              Cancel
            </Button>
            <Button
              onClick={() => {
                if (pending !== null) {
                  setEnabled(pending);
                  if (!pending) setOpen(false);
                }
                setPending(null);
              }}
            >
              {pending ? "Enable" : "Disable"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <Dialog
        open={open}
        onOpenChange={(nextOpen) => {
          if (!nextOpen || enabled) setOpen(nextOpen);
        }}
      >
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>Add Authorization</DialogTitle>
            <DialogDescription>
              Select a user to authorize for this chargepoint
            </DialogDescription>
          </DialogHeader>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              if (!enabled || !selectedUser) return;
              if (!rows.some((row) => row.id === selectedUser.id))
                setRows((current) => [...current, selectedUser]);
              setSelectedUser(undefined);
              setUserSearch("");
              setOpen(false);
            }}
          >
            <div className="mb-6">
              <label className="field-label" htmlFor="authorization-user">
                User
              </label>
              <Input
                id="authorization-user"
                disabled={!enabled}
                placeholder="Search user by name or email..."
                value={userSearch}
                onChange={(e) => {
                  if (!enabled) return;
                  setUserSearch(e.target.value);
                  setSelectedUser(undefined);
                }}
              />
              {userSearch && !selectedUser && (
                <div className="mt-2 rounded-lg border">
                  {users
                    .filter((user) =>
                      `${user.name} ${user.email}`
                        .toLowerCase()
                        .includes(userSearch.toLowerCase()),
                    )
                    .map((user) => (
                      <button
                        type="button"
                        key={user.id}
                        disabled={!enabled}
                        className="block w-full p-3 text-left hover:bg-muted"
                        onClick={() => {
                          if (!enabled) return;
                          setSelectedUser(user);
                          setUserSearch(user.name);
                        }}
                      >
                        {user.name}
                        <span className="block text-xs text-muted-foreground">
                          {user.email}
                        </span>
                      </button>
                    ))}
                </div>
              )}
              {!selectedUser && (
                <p className="mt-1 text-xs text-muted-foreground">
                  Please select a user
                </p>
              )}
            </div>
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setOpen(false)}
              >
                Cancel
              </Button>
              <Button disabled={!enabled || !selectedUser}>Add Authorization</Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
