import { useState } from "react";
import {
  getDevices,
  saveDevices,
  getMerchant,
} from "../../../utils/storage";
import { useNavigate } from "@tanstack/react-router";



export default function AddDeviceFeature() {
  const [form, setForm] = useState<DeviceData | null >(null);
  const navigate = useNavigate();

  const merchant = getMerchant();

  const isMerchantValid =
    merchant?.merchantName &&
    merchant?.tower &&
    merchant?.floor &&
    merchant?.unit;

  const isFormValid =
    form?.roomName?.trim() &&
    form?.deviceName?.trim() &&
    form?.deviceType?.trim() &&
    form?.deviceLabel?.trim();

  function handleChange(
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) {
    const { name, value } = e.target;
    setForm((prev) => ({ ...prev, [name]: value }));
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!isMerchantValid || !isFormValid) return;
    
    const devices = getDevices();
    
    const deviceToSave: DeviceData = {
      ...form,
      id: new Date().getTime().toString(),
      towerNumber: merchant.tower,
      floorName: merchant.floor,
      unitNumber: merchant.unit,
      deviceLabel: form?.deviceLabel,
    };
    
    saveDevices([...devices, deviceToSave]);
    setForm(null);
    navigate({ to: "/" });
  }

  return (
    <form onSubmit={handleSubmit} className="p-4">
      {!isMerchantValid && (
        <p className="text-sm text-red-500 mb-4">
          Lengkapi data merchant (tower, floor, unit) terlebih dahulu
        </p>
      )}

      <div className="flex flex-col gap-4">
        {/* ROOM */}
        <div>
          <label className="mb-1 text-neutral-900 block font-semibold">
            Room
          </label>
          <input
            name="roomName"
            placeholder="Room Name"
            value={form?.roomName}
            onChange={handleChange}
            className="p-2 border border-neutral-200 w-full rounded-md"
            required
          />
        </div>

        {/* DEVICE NAME */}
        <div>
          <label className="mb-1 text-neutral-900 block font-semibold">
            Device Name
          </label>
          <input
            name="deviceName"
            placeholder="Device Name"
            value={form?.deviceName}
            onChange={handleChange}
            className="p-2 border border-neutral-200 w-full rounded-md"
            required
          />
        </div>

        {/* DEVICE TYPE */}
        <div>
          <label className="mb-1 text-neutral-900 block font-semibold">
            Device Type
          </label>
          <input
            name="deviceType"
            placeholder="Device Type"
            value={form?.deviceType}
            onChange={handleChange}
            className="p-2 border border-neutral-200 w-full rounded-md"
            required
          />
        </div>

        {/* DEVICE LABEL */}
        <div>
          <label className="mb-1 text-neutral-900 block font-semibold">
            Device Label
          </label>
          <input
            name="deviceLabel"
            value={form?.deviceLabel}
            onChange={handleChange}
            className="p-2 border border-neutral-200 w-full rounded-md"
            placeholder={`${form?.roomName || "Room"} ${form?.deviceName || "Device"}`}
            required
          />
        </div>
      </div>

      <button
        type="submit"
        disabled={!isMerchantValid || !isFormValid}
        className="
          w-full py-2 rounded-lg mt-8 text-white cursor-pointer
          bg-orange-500
          disabled:bg-neutral-400
          disabled:cursor-not-allowed
        "
      >
        Add Device
      </button>
    </form>
  );
}
