// src/components/editor/RightPanel.jsx
import React, { useMemo } from "react";
import { Btn, Field, Pill, Select, TextInput } from "../../components/common/UI";
import { UI } from "../../constants/pvc";
import { money, uid } from "../../utils/helpers";
import {
  clamp,
  safeNum,
  ensureArrayCount,
  computeGeometry,
  computePositionTotals,
  mmToM,
} from "./CuttingList";

export default function RightPanel({ draft, setDraft, offer, materials, onSave }) {
  const computed = useMemo(() => {
    if (!draft) return null;
    return computePositionTotals(draft, offer, materials);
  }, [draft, offer, materials]);

  if (!draft) {
    return (
      <div style={panelStyle()}>
        <div style={{ color: UI.muted }}>Zgjedh një pozicion.</div>
      </div>
    );
  }

  return (
    <div className="rightPanel" style={{ ...panelStyle(), overflow: "auto" }}>
      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "flex-start" }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 950, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            Parametrat e pozicionit
          </div>
          <div style={{ fontSize: 12, color: UI.muted, marginTop: 2 }}>
            Totali: <b>€ {money(computed?.prices.total || 0)}</b>
          </div>
        </div>
        <Pill tone="blue">Live</Pill>
      </div>

      <div style={{ marginTop: 12, display: "grid", gap: 12 }}>
        <Field label="Emri">
          <TextInput value={draft.name || ""} onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))} />
        </Field>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <Field label="Tipi">
            <Select value={draft.isDoor ? "door" : "window"} onChange={(e) => setDraft((d) => ({ ...d, isDoor: e.target.value === "door" }))}>
              <option value="window">Dritare</option>
              <option value="door">Derë</option>
            </Select>
          </Field>

          <Field label="Forma">
            <Select value={draft.shapeType || "rect"} onChange={(e) => setDraft((d) => ({ ...d, shapeType: e.target.value }))}>
              <option value="rect">Drejtkëndësh</option>
              <option value="sloped">E pjerrët (sloped)</option>
            </Select>
          </Field>
        </div>

        {draft.shapeType === "sloped" ? (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <Field label="Offset lart majtas (mm)">
              <TextInput
                type="number"
                value={draft.topLeftOffsetMm || 0}
                onChange={(e) => setDraft((d) => ({ ...d, topLeftOffsetMm: safeNum(e.target.value, 0) }))}
              />
            </Field>
            <Field label="Offset lart djathtas (mm)">
              <TextInput
                type="number"
                value={draft.topRightOffsetMm || 0}
                onChange={(e) => setDraft((d) => ({ ...d, topRightOffsetMm: safeNum(e.target.value, 0) }))}
              />
            </Field>
          </div>
        ) : null}

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <Field label="Gjerësia (mm)">
            <TextInput type="number" value={draft.frameW || 0} onChange={(e) => setDraft((d) => ({ ...d, frameW: safeNum(e.target.value, 0) }))} />
          </Field>
          <Field label="Lartësia (mm)">
            <TextInput type="number" value={draft.frameH || 0} onChange={(e) => setDraft((d) => ({ ...d, frameH: safeNum(e.target.value, 0) }))} />
          </Field>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <Field label="Profil poshtë (mm)">
            <TextInput
              type="number"
              value={draft.extraBottomProfile || 0}
              onChange={(e) => setDraft((d) => ({ ...d, extraBottomProfile: safeNum(e.target.value, 0) }))}
            />
          </Field>
          <Field label="Roll / Persiane">
            <Select value={draft.hasRoll ? "yes" : "no"} onChange={(e) => setDraft((d) => ({ ...d, hasRoll: e.target.value === "yes" }))}>
              <option value="no">Jo</option>
              <option value="yes">Po</option>
            </Select>
          </Field>
        </div>

        {draft.hasRoll ? (
          <Field label="Lartësia e roll-it (mm)">
            <TextInput type="number" value={draft.rollHeight || 0} onChange={(e) => setDraft((d) => ({ ...d, rollHeight: safeNum(e.target.value, 0) }))} />
          </Field>
        ) : null}

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <Field label="Krahë (Sashes)">
            <TextInput
              type="number"
              value={draft.sashCount ?? (draft.sashes?.length || 1)}
              onChange={(e) => {
                const c = clamp(safeNum(e.target.value, 1), 1, 12);
                setDraft((d) => ({ ...d, sashCount: c, sashes: ensureArrayCount(d.sashes, c, () => ({ id: uid() })) }));
              }}
            />
          </Field>
          <Field label="T-profile (#)">
            <TextInput
              type="number"
              value={draft.tProfileCount ?? (draft.tProfiles?.length || 0)}
              onChange={(e) => {
                const c = clamp(safeNum(e.target.value, 0), 0, 12);
                setDraft((d) => ({ ...d, tProfileCount: c, tProfiles: ensureArrayCount(d.tProfiles, c, () => ({ id: uid() })) }));
              }}
            />
          </Field>
        </div>

        <Field label="Xhami">
          <Select value={draft.glassTypeId || ""} onChange={(e) => setDraft((d) => ({ ...d, glassTypeId: e.target.value }))}>
            {(materials.glassTypes || []).map((g) => (
              <option key={g.id} value={g.id}>
                {g.name} — € {money(g.pricePerM2)}/m²
              </option>
            ))}
          </Select>
        </Field>

        <AccessoriesEditor materials={materials} value={draft.accessories || []} onChange={(next) => setDraft((d) => ({ ...d, accessories: next }))} />

        {/* pricing */}
        <div style={{ borderTop: `1px solid ${UI.border}`, paddingTop: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
            <div style={{ fontWeight: 950 }}>Çmimi</div>
            <Pill tone="green">€ {money(computed?.prices.total || 0)}</Pill>
          </div>

          <div style={{ marginTop: 10, display: "grid", gap: 8, fontSize: 13 }}>
            <Row label="Profil (m)" value={`${money(computed?.cut.profileM || 0)} m`} />
            <Row label="Profil (€)" value={`€ ${money(computed?.prices.profileCost || 0)}`} />
            <Row label="Armaturë (€)" value={`€ ${money(computed?.prices.ironCost || 0)}`} />
            <Row label="Xham (m²)" value={`${money(computed?.glass.totalM2 || 0)} m²`} />
            <Row label="Xham (€)" value={`€ ${money(computed?.prices.glassCost || 0)}`} />
            <Row label="Aksesorë (€)" value={`€ ${money(computed?.prices.accessoriesCost || 0)}`} />
            <div style={{ borderTop: `1px dashed ${UI.border}`, marginTop: 4 }} />
            <Row label="Subtotal" value={`€ ${money(computed?.prices.subtotal || 0)}`} />
            <Row label={`Marzha (${safeNum(offer.margin, 0)}%)`} value={`€ ${money((computed?.prices.total || 0) - (computed?.prices.subtotal || 0))}`} />
            <Row label="Totali" value={`€ ${money(computed?.prices.total || 0)}`} strong />
          </div>
        </div>

        {/* cutting list */}
        <div style={{ borderTop: `1px solid ${UI.border}`, paddingTop: 12 }}>
          <div style={{ fontWeight: 950, marginBottom: 8 }}>Cutting list (përafërsisht)</div>
          <div style={{ display: "grid", gap: 8, fontSize: 13 }}>
            {/* use geometry totals from computeGeometry for normalization hints */}
            <Row label="Outer frame" value={`${money(mmToM(computed?.cut.outerMm || 0))} m`} />
            <Row label="Sash frames" value={`${money(mmToM(computed?.cut.sashTotalMm || 0))} m`} />
            <Row label="T-profiles" value={`${money(mmToM(computed?.cut.tMm || 0))} m`} />
            <div style={{ borderTop: `1px dashed ${UI.border}`, marginTop: 4 }} />
            <Row label="Total profile" value={`${money(computed?.cut.profileM || 0)} m`} strong />
            <Row label="Total iron" value={`${money(computed?.cut.ironM || 0)} m`} strong />
          </div>
        </div>

        <div style={{ display: "grid", gap: 8 }}>
          <Btn variant="primary" onClick={onSave}>
            ✔ Ruaj pozicionin
          </Btn>
        </div>
      </div>
    </div>
  );
}

/* ============================== small UI bits ============================== */

function panelStyle() {
  return {
    border: `1px solid ${UI.border}`,
    borderRadius: 18,
    background: "#fff",
    boxShadow: UI.shadow,
    padding: 14,
    minWidth: 0,
  };
}

function Row({ label, value, strong }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
      <span style={{ color: UI.muted }}>{label}</span>
      <span style={{ fontWeight: strong ? 950 : 800 }}>{value}</span>
    </div>
  );
}

function AccessoriesEditor({ materials, value, onChange }) {
  const accList = materials.accessories || [];
  const items = Array.isArray(value) ? value : [];

  return (
    <div style={{ borderTop: `1px solid ${UI.border}`, paddingTop: 12 }}>
      <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "center" }}>
        <div style={{ fontWeight: 950 }}>Aksesorë</div>
        <Btn
          variant="soft"
          onClick={() => {
            const first = accList[0];
            if (!first) return;
            onChange?.([...items, { id: first.id, qty: 1 }]);
          }}
          disabled={!accList.length}
        >
          + Shto
        </Btn>
      </div>

      {!accList.length ? (
        <div style={{ marginTop: 8, fontSize: 12, color: UI.muted }}>Nuk ka aksesorë në Materialet.</div>
      ) : items.length === 0 ? (
        <div
          style={{
            marginTop: 8,
            padding: 10,
            borderRadius: 12,
            background: UI.soft,
            border: `1px dashed ${UI.border}`,
            color: UI.muted,
            fontSize: 12,
          }}
        >
          Shto aksesorë nëse dëshiron (mekanizëm, dorezë, rrjeta, etj.).
        </div>
      ) : (
        <div style={{ marginTop: 10, display: "grid", gap: 8 }}>
          {items.map((it, idx) => (
            <div
              key={`${it.id}-${idx}`}
              style={{
                border: `1px solid ${UI.border}`,
                borderRadius: 14,
                padding: 10,
                display: "grid",
                gridTemplateColumns: "1fr 86px 44px",
                gap: 8,
                alignItems: "center",
              }}
            >
              <Select
                value={it.id}
                onChange={(e) => {
                  const next = items.map((x, i) => (i === idx ? { ...x, id: e.target.value } : x));
                  onChange?.(next);
                }}
              >
                {accList.map((a) => (
                  <option key={a.id} value={a.id}>
                    {a.name} — € {money(a.price)}
                  </option>
                ))}
              </Select>

              <TextInput
                type="number"
                value={it.qty}
                onChange={(e) => {
                  const qty = clamp(safeNum(e.target.value, 1), 0, 9999);
                  onChange?.(items.map((x, i) => (i === idx ? { ...x, qty } : x)));
                }}
              />

              <button
                onClick={() => onChange?.(items.filter((_, i) => i !== idx))}
                style={{
                  width: 36,
                  height: 36,
                  borderRadius: 12,
                  border: `1px solid ${UI.border}`,
                  background: "#fff",
                  cursor: "pointer",
                  fontWeight: 900,
                }}
                title="Hiq"
              >
                ×
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
