import { useEffect, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { ArrowLeft, MapPin, Pencil, Plus, Trash2 } from 'lucide-react';
import { api } from '../api';
import { Card, Badge, StatusBadge, Btn, Field, inputCls, Modal, Spinner, ErrorBox, Table } from '../components/ui';

const U_HEIGHT = 28; // px per U

const DEVICE_TYPES = ['server', 'switch', 'router', 'firewall', 'storage', 'ups', 'pdu', 'other'];

const TYPE_COLORS = {
  server: 'bg-blue/20 border-blue/60 text-blue',
  switch: 'bg-green/20 border-green/60 text-green',
  firewall: 'bg-red/20 border-red/60 text-red',
  storage: 'bg-purple/20 border-purple/60 text-purple',
  ups: 'bg-yellow/20 border-yellow/60 text-yellow'
};
const DEFAULT_TYPE_COLOR = 'bg-accent-soft border-accent/60 text-accent';

const STATUS_LABELS = { active: 'Actief', standby: 'Standby', decommissioned: 'Uitgefaseerd' };

const EMPTY_DEVICE = {
  name: '', device_type: 'server', model: '', manufacturer: '', position_u: 1, height_u: 1,
  mgmt_ip: '', serial: '', asset_tag: '', status: 'active', specs: '', notes: ''
};

export default function RackDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [rackModal, setRackModal] = useState(false);
  const [rackForm, setRackForm] = useState(null);
  const [deviceModal, setDeviceModal] = useState(false);
  const [editDevice, setEditDevice] = useState(null);
  const [deviceForm, setDeviceForm] = useState(EMPTY_DEVICE);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState(null);

  const load = () => {
    setError(null);
    api.get(`/racks/${id}`).then(setData).catch(setError);
  };
  useEffect(load, [id]);

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

  const { rack, devices } = data;
  const totalUnits = rack.total_units || 42;

  // ---- Rack bewerken / verwijderen ----
  const openRackEdit = () => {
    setRackForm({
      name: rack.name || '', location: rack.location || '', datacenter: rack.datacenter || '',
      total_units: totalUnits, notes: rack.notes || ''
    });
    setSaveError(null);
    setRackModal(true);
  };

  const saveRack = async (e) => {
    e.preventDefault();
    setSaving(true);
    setSaveError(null);
    try {
      await api.put(`/racks/${id}`, { ...rackForm, total_units: parseInt(rackForm.total_units, 10) || 42 });
      setRackModal(false);
      load();
    } catch (err) {
      setSaveError(err);
    } finally {
      setSaving(false);
    }
  };

  const deleteRack = async () => {
    if (!window.confirm(`Rack "${rack.name}" en alle devices verwijderen?`)) return;
    try {
      await api.del(`/racks/${id}`);
      navigate('/racks');
    } catch (err) {
      alert(err.message || String(err));
    }
  };

  // ---- Devices ----
  const openDeviceNew = () => {
    setEditDevice(null);
    setDeviceForm(EMPTY_DEVICE);
    setSaveError(null);
    setDeviceModal(true);
  };

  const openDeviceEdit = (d) => {
    setEditDevice(d);
    setDeviceForm({
      name: d.name || '', device_type: d.device_type || 'server', model: d.model || '',
      manufacturer: d.manufacturer || '', position_u: d.position_u || 1, height_u: d.height_u || 1,
      mgmt_ip: d.mgmt_ip || '', serial: d.serial || '', asset_tag: d.asset_tag || '',
      status: d.status || 'active', specs: d.specs || '', notes: d.notes || ''
    });
    setSaveError(null);
    setDeviceModal(true);
  };

  const saveDevice = async (e) => {
    e.preventDefault();
    setSaving(true);
    setSaveError(null);
    const body = {
      ...deviceForm,
      position_u: parseInt(deviceForm.position_u, 10),
      height_u: parseInt(deviceForm.height_u, 10) || 1
    };
    try {
      if (editDevice) {
        await api.put(`/racks/devices/${editDevice.id}`, body);
      } else {
        await api.post(`/racks/${id}/devices`, body);
      }
      setDeviceModal(false);
      load();
    } catch (err) {
      setSaveError(err);
    } finally {
      setSaving(false);
    }
  };

  const deleteDevice = async () => {
    if (!editDevice) return;
    if (!window.confirm(`Device "${editDevice.name}" verwijderen?`)) return;
    setSaving(true);
    setSaveError(null);
    try {
      await api.del(`/racks/devices/${editDevice.id}`);
      setDeviceModal(false);
      load();
    } catch (err) {
      setSaveError(err);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-5 fade-in">
      {/* Header */}
      <div className="flex items-start justify-between gap-3">
        <div>
          <Link to="/racks" className="text-[12px] text-muted hover:text-text flex items-center gap-1 mb-1">
            <ArrowLeft className="w-3.5 h-3.5" /> Terug naar racks
          </Link>
          <h1 className="text-xl font-bold tracking-tight">{rack.name}</h1>
          <div className="text-[13px] text-muted mt-0.5 flex items-center gap-2 flex-wrap">
            <Link to={`/clients/${rack.client_id}`} className="text-accent hover:underline">{rack.client_name}</Link>
            {(rack.location || rack.datacenter) && (
              <span className="flex items-center gap-1">
                <MapPin className="w-3.5 h-3.5" />
                {[rack.location, rack.datacenter].filter(Boolean).join(' · ')}
              </span>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <Btn variant="secondary" onClick={openRackEdit}><Pencil className="w-3.5 h-3.5" /> Bewerken</Btn>
          <Btn variant="danger" onClick={deleteRack}><Trash2 className="w-3.5 h-3.5" /> Verwijderen</Btn>
        </div>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4 items-start">
        {/* Visuele rack-weergave (U1 bovenaan) */}
        <Card
          title="Rack-overzicht"
          subtitle={`${devices.length} devices · ${totalUnits}U`}
          actions={<Btn size="sm" onClick={openDeviceNew}><Plus className="w-3.5 h-3.5" /> Device</Btn>}
        >
          <div className="flex justify-center">
            <div className="flex gap-1.5">
              {/* U-nummers */}
              <div className="flex flex-col text-right" style={{ width: 34 }}>
                {Array.from({ length: totalUnits }, (_, i) => (
                  <div key={i} className="text-[10px] text-muted flex items-center justify-end pr-1" style={{ height: U_HEIGHT }}>
                    U{i + 1}
                  </div>
                ))}
              </div>
              {/* Rack-frame */}
              <div
                className="relative border-2 border-border rounded-md bg-bg-soft overflow-hidden"
                style={{ width: 260, height: totalUnits * U_HEIGHT }}
              >
                {/* Lege posities als dunne rijen */}
                {Array.from({ length: totalUnits }, (_, i) => (
                  <div
                    key={i}
                    className="absolute left-0 right-0 border-b border-border-soft/40"
                    style={{ top: i * U_HEIGHT, height: U_HEIGHT }}
                  />
                ))}
                {/* Devices */}
                {devices.map(d => {
                  const pos = Math.max(1, Math.min(d.position_u || 1, totalUnits));
                  const h = Math.max(1, d.height_u || 1);
                  const colorCls = TYPE_COLORS[d.device_type] || DEFAULT_TYPE_COLOR;
                  return (
                    <button
                      key={d.id}
                      onClick={() => openDeviceEdit(d)}
                      title={`${d.name}${d.model ? ` — ${d.model}` : ''} (U${pos}${h > 1 ? `–U${pos + h - 1}` : ''})`}
                      className={`absolute left-1 right-1 rounded border px-2 flex flex-col justify-center overflow-hidden text-left hover:brightness-125 transition-all cursor-pointer ${colorCls}`}
                      style={{ top: (pos - 1) * U_HEIGHT + 1, height: h * U_HEIGHT - 2 }}
                    >
                      <span className="text-[11px] font-semibold truncate leading-tight">{d.name}</span>
                      {d.model && h * U_HEIGHT >= 36 && (
                        <span className="text-[10px] opacity-75 truncate leading-tight">{d.model}</span>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
          {/* Legenda */}
          <div className="flex items-center gap-3 flex-wrap mt-4 pt-3 border-t border-border-soft">
            {Object.keys(TYPE_COLORS).map(t => (
              <span key={t} className="flex items-center gap-1.5 text-[11px] text-muted">
                <span className={`w-2.5 h-2.5 rounded-sm border ${TYPE_COLORS[t]}`} /> {t}
              </span>
            ))}
            <span className="flex items-center gap-1.5 text-[11px] text-muted">
              <span className={`w-2.5 h-2.5 rounded-sm border ${DEFAULT_TYPE_COLOR}`} /> overig
            </span>
          </div>
        </Card>

        {/* Device-tabel */}
        <Card title="Devices" subtitle={`${devices.length} in dit rack`}>
          <Table
            columns={[
              { label: 'Naam', render: d => <span className="text-accent font-medium">{d.name}</span> },
              { label: 'Type', render: d => <Badge color="blue">{d.device_type}</Badge> },
              { label: 'Model', render: d => <span className="text-muted">{d.model || '-'}</span> },
              { label: 'Positie', render: d => `U${d.position_u}` },
              { label: 'Mgmt IP', render: d => <span className="text-muted">{d.mgmt_ip || '-'}</span> },
              { label: 'Status', render: d => <StatusBadge status={d.status} labels={STATUS_LABELS} /> }
            ]}
            rows={devices}
            keyFn={d => d.id}
            onRowClick={openDeviceEdit}
            empty={<div className="text-center text-muted text-[13px] py-8">Nog geen devices in dit rack</div>}
          />
        </Card>
      </div>

      {/* Rack bewerk-modal */}
      <Modal open={rackModal} onClose={() => setRackModal(false)} title="Rack bewerken">
        {rackForm && (
          <form onSubmit={saveRack} className="space-y-3">
            {saveError && <ErrorBox error={saveError} />}
            <Field label="Naam *">
              <input className={inputCls} value={rackForm.name} onChange={e => setRackForm({ ...rackForm, name: e.target.value })} required />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Locatie">
                <input className={inputCls} value={rackForm.location} onChange={e => setRackForm({ ...rackForm, location: e.target.value })} />
              </Field>
              <Field label="Datacenter">
                <input className={inputCls} value={rackForm.datacenter} onChange={e => setRackForm({ ...rackForm, datacenter: e.target.value })} />
              </Field>
            </div>
            <Field label="Aantal U">
              <input type="number" min="1" className={inputCls} value={rackForm.total_units} onChange={e => setRackForm({ ...rackForm, total_units: e.target.value })} />
            </Field>
            <Field label="Notities">
              <textarea rows={3} className={inputCls} value={rackForm.notes} onChange={e => setRackForm({ ...rackForm, notes: e.target.value })} />
            </Field>
            <div className="flex justify-end gap-2 pt-1">
              <Btn variant="secondary" type="button" onClick={() => setRackModal(false)}>Annuleren</Btn>
              <Btn type="submit" loading={saving}>Opslaan</Btn>
            </div>
          </form>
        )}
      </Modal>

      {/* Device-modal */}
      <Modal open={deviceModal} onClose={() => setDeviceModal(false)} title={editDevice ? 'Device bewerken' : 'Device toevoegen'} wide>
        <form onSubmit={saveDevice} className="space-y-3">
          {saveError && <ErrorBox error={saveError} />}
          <div className="grid grid-cols-2 gap-3">
            <Field label="Naam *">
              <input className={inputCls} value={deviceForm.name} onChange={e => setDeviceForm({ ...deviceForm, name: e.target.value })} required />
            </Field>
            <Field label="Type">
              <select className={inputCls} value={deviceForm.device_type} onChange={e => setDeviceForm({ ...deviceForm, device_type: e.target.value })}>
                {DEVICE_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
              </select>
            </Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Model">
              <input className={inputCls} value={deviceForm.model} onChange={e => setDeviceForm({ ...deviceForm, model: e.target.value })} />
            </Field>
            <Field label="Fabrikant">
              <input className={inputCls} value={deviceForm.manufacturer} onChange={e => setDeviceForm({ ...deviceForm, manufacturer: e.target.value })} />
            </Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label={`Positie U * (1–${totalUnits})`}>
              <input type="number" min="1" max={totalUnits} className={inputCls} value={deviceForm.position_u} onChange={e => setDeviceForm({ ...deviceForm, position_u: e.target.value })} required />
            </Field>
            <Field label="Hoogte (U)">
              <input type="number" min="1" max={totalUnits} className={inputCls} value={deviceForm.height_u} onChange={e => setDeviceForm({ ...deviceForm, height_u: e.target.value })} />
            </Field>
          </div>
          <div className="grid grid-cols-3 gap-3">
            <Field label="Mgmt IP">
              <input className={inputCls} value={deviceForm.mgmt_ip} onChange={e => setDeviceForm({ ...deviceForm, mgmt_ip: e.target.value })} />
            </Field>
            <Field label="Serienummer">
              <input className={inputCls} value={deviceForm.serial} onChange={e => setDeviceForm({ ...deviceForm, serial: e.target.value })} />
            </Field>
            <Field label="Asset-tag">
              <input className={inputCls} value={deviceForm.asset_tag} onChange={e => setDeviceForm({ ...deviceForm, asset_tag: e.target.value })} />
            </Field>
          </div>
          <Field label="Status">
            <select className={inputCls} value={deviceForm.status} onChange={e => setDeviceForm({ ...deviceForm, status: e.target.value })}>
              <option value="active">Actief</option>
              <option value="standby">Standby</option>
              <option value="decommissioned">Uitgefaseerd</option>
            </select>
          </Field>
          <Field label="Specs">
            <textarea rows={2} className={inputCls} value={deviceForm.specs} onChange={e => setDeviceForm({ ...deviceForm, specs: e.target.value })} />
          </Field>
          <Field label="Notities">
            <textarea rows={2} className={inputCls} value={deviceForm.notes} onChange={e => setDeviceForm({ ...deviceForm, notes: e.target.value })} />
          </Field>
          <div className="flex items-center justify-between gap-2 pt-1">
            <div>
              {editDevice && (
                <Btn variant="danger" type="button" onClick={deleteDevice} loading={saving}>
                  <Trash2 className="w-3.5 h-3.5" /> Verwijderen
                </Btn>
              )}
            </div>
            <div className="flex gap-2">
              <Btn variant="secondary" type="button" onClick={() => setDeviceModal(false)}>Annuleren</Btn>
              <Btn type="submit" loading={saving}>Opslaan</Btn>
            </div>
          </div>
        </form>
      </Modal>
    </div>
  );
}
