import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';

type Service = {
  id: number;
  name: string;
  slug: string;
  color: string;
};

export default function OptionsPage() {
  const { services } = usePage().props as { services: Service[] };

  const [rows, setRows] = useState<Service[]>(services);

  const updateColor = (id: number, color: string) => {
    setRows((prev) =>
      prev.map((s) => (s.id === id ? { ...s, color } : s))
    );
  };

  const save = () => {
    router.put(
      '/options/service-colors',
      { services: rows },
      { preserveScroll: true }
    );
  };

  return (
    <>
      <Head title="Options" />

      <div className="gd-page-edit">
        <div className="gd-form-card">

          <h4 className="mb-4">Service Colors</h4>

          {rows.map((service) => (
            <div
              key={service.id}
              style={{
                display: 'flex',
                alignItems: 'center',
                marginBottom: '14px',
                gap: '12px',
              }}
            >
              <div style={{ width: 260 }}>
                {service.name}
              </div>

              <input
                type="color"
                value={service.color}
                onChange={(e) =>
                  updateColor(service.id, e.target.value)
                }
                style={{
                  width: 60,
                  height: 36,
                  border: 'none',
                  background: 'none',
                  cursor: 'pointer',
                }}
              />

              <div
                style={{
                  flex: 1,
                  height: 20,
                  background: service.color,
                  borderRadius: 4,
                }}
              />
            </div>
          ))}

          <div style={{ marginTop: 20 }}>
            <button
              onClick={save}
              className="btn btn-primary"
            >
              Save Colors
            </button>
          </div>
        </div>
      </div>
    </>
  );
}