import React, { useEffect, useMemo, useState } from "react";
import { UI } from "../../constants/ui";
import { Pill } from "../../components/ui/Pill";
import { Btn } from "../../components/ui/Btn";
import { Modal } from "../../components/ui/Modal";
import { Field } from "../../components/ui/Field";
import { TextInput, Select } from "../../components/ui/Inputs";
import { money } from "../../utils/money";
import { OfferCard } from "./OfferCard";

export function OffersDashboard({ offers, materials, onOpenOffer, onCreateOffer, onOpenMaterials }) {
  const [q, setQ] = useState("");
  const [createOpen, setCreateOpen] = useState(false);

  const [name, setName] = useState("");
  const [margin, setMargin] = useState(20);
  const [color, setColor] = useState("[BB] Bardhë-Bardhë");
  const [profileId, setProfileId] = useState(materials.profiles[0]?.id || "");
  const [ironId, setIronId] = useState(materials.irons[0]?.id || "");

  useEffect(() => {
    setProfileId((p) => p || materials.profiles[0]?.id || "");
    setIronId((i) => i || materials.irons[0]?.id || "");
  }, [materials.profiles, materials.irons]);

  const filtered = useMemo(() => {
    const s = q.trim().toLowerCase();
    if (!s) return offers;
    return offers.filter((o) => (o.name || "").toLowerCase().includes(s));
  }, [offers, q]);

  const totalAll = useMemo(
    () => offers.reduce((sum, o) => sum + (o.positions || []).reduce((s, p) => s + (p.total || 0), 0), 0),
    [offers]
  );

  return (
    <div>
      <div className="stickyHeader">
        <div
          style={{
            maxWidth: 1240,
            margin: "0 auto",
            padding: "14px 18px",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 12,
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
            <div
              style={{
                width: 38,
                height: 38,
                borderRadius: 12,
                background: UI.primary,
                color: "#fff",
                display: "grid",
                placeItems: "center",
                fontWeight: 900,
              }}
            >
              PVC
            </div>

            <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.1, minWidth: 0 }}>
              <div style={{ fontWeight: 900, fontSize: 14, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                Ofertat PVC
              </div>
              <div style={{ fontSize: 12, color: UI.muted }}>Oferta • Pozicione • Print skicë</div>
            </div>

            <div style={{ marginLeft: 10, display: "flex", gap: 8, flexWrap: "wrap" }}>
              <Pill tone="soft">Totali: € {money(totalAll)}</Pill>
              <Btn
                variant="soft"
                onClick={onOpenMaterials}
                style={{ padding: "8px 10px", borderRadius: 999 }}
                title="Menaxho çmimet për profile, armaturë, xham, aksesorë"
              >
                ⚙ Materialet
              </Btn>
              <Pill tone="blue">
                P:{materials.profiles.length} • A:{materials.irons.length} • X:{materials.glassTypes.length} • AK:{materials.accessories.length}
              </Pill>
            </div>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 320, maxWidth: "40vw" }}>
              <TextInput value={q} onChange={(e) => setQ(e.target.value)} placeholder="Kërko ofertë…" style={{ background: UI.soft }} />
            </div>
            <Btn
              variant="primary"
              onClick={() => {
                setName("");
                setMargin(20);
                setColor("[BB] Bardhë-Bardhë");
                setProfileId(materials.profiles[0]?.id || "");
                setIronId(materials.irons[0]?.id || "");
                setCreateOpen(true);
              }}
            >
              + Ofertë e re
            </Btn>
          </div>
        </div>
      </div>

      <div className="wrap">
        {filtered.length === 0 ? (
          <div style={{ border: `1px dashed ${UI.border}`, borderRadius: 18, padding: 28, background: UI.soft, color: UI.muted }}>
            Nuk u gjet asnjë ofertë.
          </div>
        ) : (
          <div className="offersGrid">
            {filtered.map((o) => (
              <OfferCard key={o.id} offer={o} materials={materials} onOpen={() => onOpenOffer(o.id)} />
            ))}
          </div>
        )}
      </div>

      <Modal
        open={createOpen}
        title="Krijo ofertë të re"
        onClose={() => setCreateOpen(false)}
        footer={
          <div style={{ display: "flex", justifyContent: "space-between", gap: 10 }}>
            <Btn variant="ghost" onClick={() => setCreateOpen(false)}>
              Anulo
            </Btn>
            <Btn
              variant="primary"
              onClick={() => {
                if (!name.trim()) return;
                onCreateOffer({ name: name.trim(), margin: Number(margin) || 0, color, profileId, ironId });
                setCreateOpen(false);
              }}
              disabled={!name.trim() || !profileId || !ironId}
            >
              Krijo ofertën
            </Btn>
          </div>
        }
      >
        <div style={{ display: "grid", gap: 12 }}>
          <Field label="Emri i ofertës">
            <TextInput value={name} onChange={(e) => setName(e.target.value)} placeholder="p.sh. Oferta – Klienti X" />
          </Field>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Field label="Marzha (%)">
              <TextInput type="number" value={margin} onChange={(e) => setMargin(Number(e.target.value) || 0)} />
            </Field>
            <Field label="Ngjyra">
              <Select value={color} onChange={(e) => setColor(e.target.value)}>
                <option value="[BB] Bardhë-Bardhë">[BB] Bardhë-Bardhë</option>
                <option value="Antracit">Antracit</option>
                <option value="Golden Oak">Golden Oak</option>
              </Select>
            </Field>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Field label="Profili default">
              <Select value={profileId} onChange={(e) => setProfileId(e.target.value)}>
                {materials.profiles.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name} — € {money(p.pricePerM)}/m
                  </option>
                ))}
              </Select>
            </Field>

            <Field label="Armatura default">
              <Select value={ironId} onChange={(e) => setIronId(e.target.value)}>
                {materials.irons.map((i) => (
                  <option key={i.id} value={i.id}>
                    {i.name} — € {money(i.pricePerM)}/m
                  </option>
                ))}
              </Select>
            </Field>
          </div>
        </div>
      </Modal>
    </div>
  );
}
