"use client";
import { useState } from "react";
import { RefreshCw, Check } from "lucide-react";
import { Panel, EmptyState } from "@/components/shared/panel";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { FormField, SelectField } from "@/components/shared/form-field";
import type { DeviceConfiguration } from "./types";
export function DeviceSettings({
  tab,
  configurations,
}: {
  tab: "configuration" | "firmware" | "diagnostic-logs";
  configurations: DeviceConfiguration[];
}) {
  const [rows, setRows] = useState(configurations);
  const [editing, setEditing] = useState<string>();
  const [protocol, setProtocol] = useState("FTP");
  const [message, setMessage] = useState("");
  const [diagnostics, setDiagnostics] = useState<
    { id: string; date: string; protocol: string }[]
  >([]);
  if (tab === "configuration")
    return (
      <Panel
        title="Configuration"
        actions={
          <Button
            variant="outline"
            size="sm"
            onClick={() =>
              setMessage("Configuration refreshed from mock data.")
            }
          >
            <RefreshCw />
            Refresh
          </Button>
        }
      >
        <div className="overflow-x-auto">
          <table className="data-table min-w-[600px]">
            <thead>
              <tr>
                {["Key", "Value", "Editable?", "Actions"].map((label) => (
                  <th key={label}>{label}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((row) => (
                <tr key={row.key}>
                  <td>{row.key}</td>
                  <td className="text-center">{row.value}</td>
                  <td className="text-center">
                    {row.editable ? (
                      <Check className="mx-auto size-4 text-success" />
                    ) : (
                      "—"
                    )}
                  </td>
                  <td className="text-center">
                    <Button
                      variant="secondary"
                      size="sm"
                      disabled={!row.editable}
                      onClick={() => setEditing(row.key)}
                    >
                      Change
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {message && (
          <p role="status" className="mt-4 text-success">
            {message}
          </p>
        )}
        <Dialog
          open={!!editing}
          onOpenChange={(open) => {
            if (!open) setEditing(undefined);
          }}
        >
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle>Change Configuration</DialogTitle>
              <DialogDescription>{editing}</DialogDescription>
            </DialogHeader>
            <form
              onSubmit={(e) => {
                e.preventDefault();
                const value = String(
                  new FormData(e.currentTarget).get("value"),
                );
                setRows(
                  rows.map((row) =>
                    row.key === editing ? { ...row, value } : row,
                  ),
                );
                setEditing(undefined);
                setMessage("Configuration updated in this preview.");
              }}
            >
              <FormField
                name="value"
                label="Value"
                type="number"
                min={1}
                required
                defaultValue={rows.find((row) => row.key === editing)?.value}
              />
              <DialogFooter className="mt-6">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setEditing(undefined)}
                >
                  Cancel
                </Button>
                <Button>Save Changes</Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </Panel>
    );
  if (tab === "firmware")
    return (
      <Panel title="Firmware" description="Current version: —">
        <form
          className="grid items-end gap-4 sm:grid-cols-4"
          onSubmit={(e) => {
            e.preventDefault();
            setMessage("Firmware update simulated in this preview.");
          }}
        >
          <SelectField
            name="protocol"
            label="Protocol"
            options={["HTTPS", "FTP"]}
          />
          <SelectField
            className="sm:col-span-2"
            name="firmware"
            label="Select Firmware"
            required
            options={[
              { value: "", label: "Pilih firmware" },
              { value: "demo-1.0", label: "Demo firmware 1.0" },
            ]}
          />
          <Button>Update</Button>
        </form>
        {message && (
          <p
            role="status"
            className="mt-4 rounded-lg bg-success/10 px-3 py-2 text-success"
          >
            {message}
          </p>
        )}
      </Panel>
    );
  return (
    <div className="space-y-6">
      <form
        className="flex flex-wrap items-end gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          const data = new FormData(e.currentTarget);
          if (String(data.get("start")) > String(data.get("end"))) {
            setMessage("End time must be after start time.");
            return;
          }
          setDiagnostics([
            ...diagnostics,
            {
              id: `diagnostic-${diagnostics.length + 1}`,
              date: String(data.get("start")),
              protocol,
            },
          ]);
          setMessage("Diagnostics request simulated in this preview.");
        }}
      >
        <div className="flex rounded-lg border border-primary">
          {["FTP", "HTTP"].map((value) => (
            <button
              key={value}
              type="button"
              aria-pressed={protocol === value}
              className={`px-4 py-3 ${protocol === value ? "bg-primary text-primary-foreground" : "text-primary"}`}
              onClick={() => setProtocol(value)}
            >
              {value}
            </button>
          ))}
        </div>
        <FormField
          name="start"
          label="Start Time"
          type="datetime-local"
          required
          defaultValue="2026-09-30T09:00"
        />
        <FormField
          name="end"
          label="End Time"
          type="datetime-local"
          required
          defaultValue="2026-09-30T10:00"
        />
        <Button>Trigger Request</Button>
      </form>
      {message && (
        <p role="status" className="text-muted-foreground">
          {message}
        </p>
      )}
      <Panel title="Diagnostic Logs">
        <table className="data-table">
          <thead>
            <tr>
              <th>Filename</th>
              <th>Protocol</th>
              <th>Created At</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {diagnostics.map((row) => (
              <tr key={row.id}>
                <td>{row.id}.log</td>
                <td>{row.protocol}</td>
                <td>{row.date}</td>
                <td>Requested</td>
              </tr>
            ))}
          </tbody>
        </table>
        {!diagnostics.length && (
          <EmptyState
            title="No diagnostics found"
            description="Trigger a request to collect diagnostic logs."
          />
        )}
      </Panel>
    </div>
  );
}
