"use client";
import { useState } from "react";
import { DataTable } from "@/components/shared/data-table";
import {
  Panel,
  PreviewNotice,
  StatusBadge,
  DetailList,
} from "@/components/shared/page";
import { Field, SelectField, TextareaField } from "@/components/shared/field";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { dateTime } from "@/lib/format";
import { usePeople } from "@/features/people/people-provider";
import { configurations, logFixtures } from "./fixtures";
import { validateConfiguration, type Chargepoint } from "./model";
export function DeviceTabs({
  tab,
  point,
  editable,
}: {
  tab: string;
  point: Chargepoint;
  editable: boolean;
}) {
  const [config, setConfig] = useState(configurations),
    [editConfig, setEditConfig] = useState<
      (typeof configurations)[number] | null
    >(null),
    [payload, setPayload] = useState<string | null>(null),
    [command, setCommand] = useState<string | null>(null),
    [notice, setNotice] = useState(""),
    [error, setError] = useState(""),
    [authorized, setAuthorized] = useState(["customer-1", "customer-2"]),
    [authEnabled, setAuthEnabled] = useState(true),
    [addingAuth, setAddingAuth] = useState(false),
    [newAuth, setNewAuth] = useState(""),
    [firmware, setFirmware] = useState<string[]>([]),
    [diagnostics, setDiagnostics] = useState<
      { id: string; file: string; size: string; date: string; status: string }[]
    >([]);
  const { people } = usePeople();
  const allowed = people.filter((p) => authorized.includes(p.id));
  const connectorRows = Array.from({ length: point.connectors }, (_, i) => ({
    id: `connector-${i + 1}`,
    number: i + 1,
    status:
      point.online === "Offline"
        ? "Unavailable"
        : i === 0
          ? "Available"
          : "Charging",
    type: i === 0 ? "CCS2" : "Type 2",
    power: point.power / point.connectors,
    energy: i === 0 ? 0 : 18.4,
  }));
  return (
    <div className="space-y-5">
      {notice && (
        <p role="status" className="text-success">
          {notice}
        </p>
      )}
      {tab === "overview" ? (
        <div className="grid gap-5 md:grid-cols-2">
          <Panel title="Device Information">
            <DetailList
              items={{
                Manufacturer: point.vendor || "—",
                Model: point.model || "—",
                "Firmware Version": point.firmware,
                "Box Serial Number": point.serial,
                "CP Serial Number": point.serial,
                "Meter Type": "DC_ENERGY",
              }}
            />
          </Panel>
          <Panel title="Network & Metering">
            <DetailList
              items={{
                Protocol: point.protocol,
                "Static Endpoint": point.endpoint,
                "Total Power": `${point.power} kW`,
                ICCID: "—",
                IMSI: "—",
                "Last Heartbeat": "15 Oct 2026 10:30 GMT+7",
              }}
            />
          </Panel>
          <Panel title="Connector Status">
            <DetailList
              items={{
                Available: point.online === "Online" ? 1 : 0,
                Charging: point.online === "Online" ? 1 : 0,
                Unavailable: point.online === "Offline" ? 2 : 0,
                Faulted: 0,
              }}
            />
          </Panel>
          <Panel title="Metadata">
            <DetailList
              items={{
                Organization: "TIAR",
                Visibility: point.visibility,
                Location: point.location,
                "Created At": "1 Oct 2026",
              }}
            />
          </Panel>
        </div>
      ) : tab === "connectors" ? (
        <>
          <DataTable
            title="Connectors"
            rows={connectorRows}
            columns={[
              { key: "number", label: "Connector" },
              { key: "type", label: "Type" },
              {
                key: "status",
                label: "Status",
                render: (r) => <StatusBadge>{r.status}</StatusBadge>,
              },
              { key: "power", label: "Power (kW)" },
              { key: "energy", label: "Energy (kWh)" },
            ]}
            actions={
              editable
                ? (r) => (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() =>
                        setCommand(
                          `Connector ${r.number}: ${r.status === "Charging" ? "Stop Transaction" : "Start Transaction"}`,
                        )
                      }
                    >
                      Controls
                    </Button>
                  )
                : undefined
            }
          />
          {editable && (
            <Panel title="Device Commands">
              <div className="flex flex-wrap gap-3 p-5">
                {[
                  "Reset",
                  "Unlock Connector",
                  "Clear Cache",
                  "Trigger Message",
                  "Data Transfer",
                ].map((c) => (
                  <Button
                    key={c}
                    variant="outline"
                    onClick={() => setCommand(c)}
                  >
                    {c}
                  </Button>
                ))}
              </div>
            </Panel>
          )}
        </>
      ) : tab === "authorizations" ? (
        <>
          <Panel title="Authorization Settings">
            <label className="flex items-center justify-between gap-4 p-5">
              <span>
                <span className="block font-medium">Enable Authorization</span>
                <span className="mt-1 block text-sm text-muted-foreground">
                  Allow selected users to access this chargepoint.
                </span>
              </span>
              <input
                type="checkbox"
                disabled={!editable}
                checked={authEnabled}
                onChange={(e) => {
                  setAuthEnabled(e.target.checked);
                  setNotice("Authorization setting changed in local preview.");
                }}
              />
            </label>
          </Panel>
          <DataTable
            title="Authorizations"
            rows={allowed}
            columns={[
              { key: "name", label: "Name" },
              { key: "email", label: "Email" },
              { key: "phone", label: "Phone" },
              { key: "role", label: "Role" },
            ]}
            onCreate={editable ? () => setAddingAuth(true) : undefined}
            createLabel="Add User"
            actions={
              editable
                ? (r) => (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setAuthorized((all) => all.filter((id) => id !== r.id));
                        setNotice("User authorization removed locally.");
                      }}
                    >
                      Remove
                    </Button>
                  )
                : undefined
            }
          />
        </>
      ) : tab === "configuration" ? (
        <DataTable
          title="Configuration"
          rows={config}
          columns={[
            { key: "key", label: "Key" },
            { key: "value", label: "Value" },
            {
              key: "editable",
              label: "Editable?",
              render: (r) => (r.editable ? "Yes" : "No"),
            },
          ]}
          actions={
            editable
              ? (r) => (
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={!r.editable}
                    onClick={() => {
                      setError("");
                      setEditConfig({ ...r });
                    }}
                  >
                    Edit
                  </Button>
                )
              : undefined
          }
        />
      ) : tab === "logs" || tab === "events" ? (
        <DataTable
          title={tab === "logs" ? "OCPP Logs" : "Events"}
          rows={logFixtures}
          columns={[
            { key: "time", label: "Time", render: (r) => dateTime(r.time) },
            { key: "type", label: "Message Type" },
            { key: "direction", label: "Direction" },
          ]}
          filters={[
            {
              key: "type",
              label: "Message Type",
              options: ["Heartbeat", "StatusNotification", "BootNotification"],
            },
          ]}
          actions={(r) => (
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPayload(r.payload)}
            >
              View Payload
            </Button>
          )}
        />
      ) : tab === "firmware" ? (
        <Panel title="Firmware">
          <div className="space-y-5 p-5">
            <PreviewNotice>
              Files are inspected locally. No firmware is uploaded or installed.
            </PreviewNotice>
            <p>
              Current firmware: <strong>{point.firmware}</strong>
            </p>
            {editable && (
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  const file = new FormData(e.currentTarget).get(
                    "firmware",
                  ) as File | null;
                  if (
                    !file?.size ||
                    file.size > 50 * 1024 * 1024 ||
                    !/\.(bin|hex|zip)$/i.test(file.name)
                  ) {
                    setError("Choose a .bin, .hex or .zip file up to 50 MB.");
                    return;
                  }
                  setFirmware((all) => [file.name, ...all]);
                  setError("");
                  setNotice(
                    "Firmware file added to local preview. No installation occurred.",
                  );
                  e.currentTarget.reset();
                }}
              >
                <Field
                  label="Firmware File"
                  name="firmware"
                  type="file"
                  accept=".bin,.hex,.zip"
                  required
                />
                <div className="mt-4 flex gap-3">
                  <Button>Preview Upload</Button>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setCommand("Update Firmware")}
                  >
                    Update Firmware
                  </Button>
                </div>
              </form>
            )}
            {error && (
              <p role="alert" className="text-destructive">
                {error}
              </p>
            )}
            {firmware.length ? (
              <ul className="divide-y">
                {firmware.map((f, i) => (
                  <li className="flex justify-between py-3" key={f + i}>
                    <span>{f}</span>
                    <span className="text-muted-foreground">Local preview</span>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="text-sm text-muted-foreground">
                No uploaded firmware files in this preview.
              </p>
            )}
          </div>
        </Panel>
      ) : tab === "diagnostic-logs" ? (
        <>
          <PreviewNotice>
            Diagnostic requests create fixture entries. No charger is contacted.
          </PreviewNotice>
          {editable && (
            <Button
              onClick={() => {
                setDiagnostics((all) => [
                  {
                    id: `diag-${all.length + 1}`,
                    file: `diagnostics-preview-${all.length + 1}.log`,
                    size: "2 KB",
                    date: "2026-10-15T10:30:00+07:00",
                    status: "Available",
                  },
                  ...all,
                ]);
                setNotice("Diagnostic fixture generated locally.");
              }}
            >
              Request Diagnostics Preview
            </Button>
          )}
          <DataTable
            title="Diagnostic Logs"
            rows={diagnostics}
            columns={[
              { key: "file", label: "Name" },
              { key: "size", label: "Size" },
              {
                key: "date",
                label: "Created At",
                render: (r) => dateTime(r.date),
              },
              {
                key: "status",
                label: "Status",
                render: (r) => <StatusBadge>{r.status}</StatusBadge>,
              },
            ]}
            actions={(r) => (
              <Button
                variant="outline"
                size="sm"
                onClick={() =>
                  setPayload(
                    `TIAR local diagnostic fixture\nChargepoint: ${point.name}\nFile: ${r.file}\nStatus: No charger contacted`,
                  )
                }
              >
                View Log
              </Button>
            )}
          />
        </>
      ) : null}
      <Dialog
        open={!!editConfig}
        onOpenChange={(open) => {
          if (!open) setEditConfig(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Change Configuration</DialogTitle>
            <DialogDescription>
              {editConfig?.key} · local preview
            </DialogDescription>
          </DialogHeader>
          {editConfig && (
            <form
              onSubmit={(e) => {
                e.preventDefault();
                const issue = validateConfiguration(
                  editConfig.value,
                  editConfig.key,
                );
                if (issue) {
                  setError(issue);
                  return;
                }
                setConfig((all) =>
                  all.map((c) => (c.id === editConfig.id ? editConfig : c)),
                );
                setEditConfig(null);
                setNotice("Configuration updated locally.");
              }}
            >
              <Field
                label="Value"
                required
                value={editConfig.value}
                onChange={(e) =>
                  setEditConfig({ ...editConfig, value: e.target.value })
                }
              />
              {error && (
                <p role="alert" className="mt-3 text-destructive">
                  {error}
                </p>
              )}
              <div className="mt-5 flex justify-end gap-2">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setEditConfig(null)}
                >
                  Cancel
                </Button>
                <Button>Save Preview</Button>
              </div>
            </form>
          )}
        </DialogContent>
      </Dialog>
      <Dialog
        open={!!payload}
        onOpenChange={(open) => {
          if (!open) setPayload(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Payload Details</DialogTitle>
            <DialogDescription>Deterministic fixture data</DialogDescription>
          </DialogHeader>
          <pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all rounded-lg bg-muted p-4 text-xs">
            {payload}
          </pre>
        </DialogContent>
      </Dialog>
      <Dialog
        open={!!command}
        onOpenChange={(open) => {
          if (!open) setCommand(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{command}</DialogTitle>
            <DialogDescription>
              Preview only. No command is sent to a charger.
            </DialogDescription>
          </DialogHeader>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              setNotice(
                `${command} preview prepared. No device command was sent.`,
              );
              setCommand(null);
            }}
          >
            <div className="mb-5 space-y-4">
              <SelectField
                label="Connector"
                name="connector"
                options={["1", "2"]}
              />
              {command === "Reset" && (
                <SelectField label="Reset Type" options={["Soft", "Hard"]} />
              )}
              <TextareaField
                label="Command Parameters (optional)"
                name="parameters"
                placeholder="Local preview parameters"
              />
            </div>
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setCommand(null)}
              >
                Cancel
              </Button>
              <Button>Confirm Preview</Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
      <Dialog open={addingAuth} onOpenChange={setAddingAuth}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add Authorized User</DialogTitle>
            <DialogDescription>
              Assign a fixture user in local preview.
            </DialogDescription>
          </DialogHeader>
          <SelectField
            label="User"
            value={newAuth}
            options={[
              { value: "", label: "Select user" },
              ...people
                .filter((p) => !authorized.includes(p.id))
                .map((p) => ({ value: p.id, label: `${p.name} · ${p.email}` })),
            ]}
            onChange={(e) => setNewAuth(e.target.value)}
          />
          <DialogFooter>
            <Button variant="outline" onClick={() => setAddingAuth(false)}>
              Cancel
            </Button>
            <Button
              disabled={!newAuth}
              onClick={() => {
                setAuthorized((all) => [...all, newAuth]);
                setAddingAuth(false);
                setNewAuth("");
                setNotice("User authorization added locally.");
              }}
            >
              Add Preview
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
