import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Plus, MapPin, Server } from 'lucide-react';
import { api } from '../api';
import { Card, Btn, Field, inputCls, Modal, Spinner, EmptyState, ErrorBox } from '../components/ui';

const EMPTY_FORM = { client_id: '', name: '', location: '', datacenter: '', total_units: 42, notes: '' };

export default function Racks() {
  const [racks, setRacks] = useState(null);
  const [error, setError] = useState(null);
  const [clients, setClients] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState(null);

  const load = () => {
    setError(null);
    api.get('/racks').then(setRacks).catch(setError);
  };
  useEffect(load, []);

  useEffect(() => {
    api.get('/clients').then(setClients).catch(() => {});
  }, []);

  const openNew = () => {
    setForm(EMPTY_FORM);
    setSaveError(null);
    setModalOpen(true);
  };

  const save = async (e) => {
    e.preventDefault();
    setSaving(true);
    setSaveError(null);
    try {
      await api.post('/racks', { ...form, total_units: parseInt(form.total_units, 10) || 42 });
      setModalOpen(false);
      load();
    } catch (err) {
      setSaveError(err);
    } finally {
      setSaving(false);
    }
  };

  if (error) return <ErrorBox error={error} onRetry={load} />;
  if (!racks) return <Spinner />;

  return (
    <div className="space-y-5 fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold tracking-tight">Racks</h1>
          <p className="text-[13px] text-muted mt-0.5">Rack-inventaris per cliënt</p>
        </div>
        <Btn onClick={openNew}><Plus className="w-4 h-4" /> Nieuw rack</Btn>
      </div>

      {racks.length === 0 ? (
        <Card>
          <EmptyState
            icon={Server}
            title="Nog geen racks"
            hint="Maak je eerste rack aan om devices toe te voegen."
            action={<Btn onClick={openNew}><Plus className="w-4 h-4" /> Nieuw rack</Btn>}
          />
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {racks.map(r => {
            const total = r.total_units || 42;
            const used = r.device_count || 0;
            const pct = Math.min(100, Math.round((used / total) * 100));
            return (
              <div key={r.id} className="bg-card border border-border-soft rounded-xl p-4 card-hover">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <Link to={`/racks/${r.id}`} className="text-[14px] font-semibold text-accent hover:underline truncate block">
                      {r.name}
                    </Link>
                    <div className="text-[12px] text-muted mt-0.5">{r.client_name}</div>
                  </div>
                  <div className="w-9 h-9 rounded-lg bg-accent-soft flex items-center justify-center shrink-0">
                    <Server className="w-[18px] h-[18px] text-accent" />
                  </div>
                </div>
                {(r.location || r.datacenter) && (
                  <div className="flex items-center gap-1.5 text-[12px] text-muted mt-2">
                    <MapPin className="w-3.5 h-3.5 shrink-0" />
                    <span className="truncate">{[r.location, r.datacenter].filter(Boolean).join(' · ')}</span>
                  </div>
                )}
                <div className="mt-3">
                  <div className="flex items-center justify-between text-[12px] mb-1">
                    <span className="text-muted">Bezetting</span>
                    <span>{used} / {total}U bezet</span>
                  </div>
                  <div className="h-1.5 bg-bg-soft rounded-full overflow-hidden">
                    <div className="h-full bg-accent rounded-full" style={{ width: `${pct}%` }} />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      <Modal open={modalOpen} onClose={() => setModalOpen(false)} title="Nieuw rack">
        <form onSubmit={save} className="space-y-3">
          {saveError && <ErrorBox error={saveError} />}
          <Field label="Cliënt *">
            <select className={inputCls} value={form.client_id} onChange={e => setForm({ ...form, client_id: e.target.value })} required>
              <option value="">— Kies cliënt —</option>
              {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </Field>
          <Field label="Naam *">
            <input className={inputCls} value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Locatie">
              <input className={inputCls} value={form.location} onChange={e => setForm({ ...form, location: e.target.value })} />
            </Field>
            <Field label="Datacenter">
              <input className={inputCls} value={form.datacenter} onChange={e => setForm({ ...form, datacenter: e.target.value })} />
            </Field>
          </div>
          <Field label="Aantal U">
            <input type="number" min="1" className={inputCls} value={form.total_units} onChange={e => setForm({ ...form, total_units: e.target.value })} />
          </Field>
          <Field label="Notities">
            <textarea rows={3} className={inputCls} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} />
          </Field>
          <div className="flex justify-end gap-2 pt-1">
            <Btn variant="secondary" type="button" onClick={() => setModalOpen(false)}>Annuleren</Btn>
            <Btn type="submit" loading={saving}>Opslaan</Btn>
          </div>
        </form>
      </Modal>
    </div>
  );
}
