"use client";

import { useState } from "react";
import { API_URL } from '@/lib/api';

interface AddMachineModalProps {
  onClose: () => void;
  onMachineAdded: () => void;
}

export default function AddMachineModal({
  onClose,
  onMachineAdded,
}: AddMachineModalProps) {
  const [form, setForm] = useState({
    customerId: "",
    manufacturer: "",
    model: "",
    serialNumber: "",
    installationDate: "",
    warrantyExpiryDate: "",
    amcExpiryDate: "",
    assignedEngineer: "",
    notes: "",
  });

  function updateField(field: string, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    const res = await fetch(`${API_URL}/api/machines`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        ...form,
        customerId: Number(form.customerId),
      }),
    });

    if (res.ok) {
      onMachineAdded();
      onClose();
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 px-4">
      <div className="w-full max-w-3xl rounded-2xl bg-white p-8 shadow-2xl">
        <h2 className="text-2xl font-bold text-slate-900">Add Machine</h2>
        <p className="mb-6 mt-1 text-sm text-slate-500">
          Add installed equipment for a customer.
        </p>

        <form onSubmit={handleSubmit} className="grid grid-cols-2 gap-4">
          {[
            ["customerId", "Customer ID"],
            ["manufacturer", "Manufacturer"],
            ["model", "Model"],
            ["serialNumber", "Serial Number"],
            ["installationDate", "Installation Date"],
            ["warrantyExpiryDate", "Warranty Expiry"],
            ["amcExpiryDate", "AMC Expiry"],
            ["assignedEngineer", "Assigned Engineer"],
          ].map(([field, label]) => (
            <div key={field}>
              <label className="mb-1 block text-sm font-medium text-slate-700">
                {label}
              </label>
              <input
                type={
                  field.includes("Date") || field.includes("Expiry")
                    ? "date"
                    : "text"
                }
                value={form[field as keyof typeof form]}
                onChange={(e) => updateField(field, e.target.value)}
                className="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
              />
            </div>
          ))}

          <div className="col-span-2">
            <label className="mb-1 block text-sm font-medium text-slate-700">
              Notes
            </label>
            <textarea
              value={form.notes}
              onChange={(e) => updateField("notes", e.target.value)}
              className="h-24 w-full rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
            />
          </div>

          <div className="col-span-2 mt-4 flex justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              className="rounded-xl border border-slate-200 px-5 py-3 font-semibold text-slate-700"
            >
              Cancel
            </button>

            <button
              type="submit"
              className="rounded-xl bg-[#EE302B] px-5 py-3 font-semibold text-white"
            >
              Save Machine
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}