import { useMemo, useState } from "react";

const customers = [
  { id: "c-001", name: "Max Muster", email: "max@example.test", type: "Kunde" },
  { id: "c-002", name: "Anna Beispiel", email: "anna@example.test", type: "Kundin" },
  { id: "c-003", name: "David Intern", email: "david@example.test", type: "Mitarbeiter" },
];

function Pill({ children, bg, color }) {
  return <span style={{ background: bg, color, borderRadius: 999, padding: "3px 9px", fontSize: 11, fontWeight: 600 }}>{children}</span>;
}

function Card({ title, children, action }) {
  return (
    <div style={{ background: "#fff", border: "1px solid #D3D1C7", borderRadius: 8, padding: "16px 18px", marginBottom: 14 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ fontSize: 10, fontWeight: 600, color: "#888780", textTransform: "uppercase", letterSpacing: 0.5 }}>{title}</div>
        {action}
      </div>
      {children}
    </div>
  );
}

export default function EQ05KundeZuordnenWechseln() {
  const [assignment, setAssignment] = useState("customer");
  const [selectedCustomerId, setSelectedCustomerId] = useState("c-001");
  const [search, setSearch] = useState("");
  const [changeNote, setChangeNote] = useState("Gerät wurde als Kundenequipment identifiziert.");
  const [message, setMessage] = useState("");

  const selectedCustomer = customers.find((c) => c.id === selectedCustomerId);
  const filteredCustomers = customers.filter((c) => `${c.name} ${c.email} ${c.type}`.toLowerCase().includes(search.toLowerCase()));

  const effect = useMemo(() => {
    if (assignment === "unassigned") {
      return { quality: "needs_review", workflow: false, hint: "Zuordnung unbestimmt: Datensatz sollte geprüft und für relevante Workflows gesperrt werden." };
    }
    if (assignment === "customer" && !selectedCustomerId) {
      return { quality: "incomplete", workflow: false, hint: "Bei Kundenzuordnung muss ein Kunde ausgewählt werden." };
    }
    return { quality: "complete", workflow: true, hint: "Zuordnung ist ausreichend geklärt. Workflow-Fähigkeit hängt zusätzlich von den übrigen Equipment-Daten ab." };
  }, [assignment, selectedCustomerId]);

  function save() {
    if (assignment === "customer" && !selectedCustomerId) {
      setMessage("Kunde fehlt: Bitte Kundendatensatz auswählen oder Zuordnung ändern.");
      return;
    }
    if (!changeNote.trim()) {
      setMessage("Änderungsnotiz empfohlen: Bitte Grund des Zuordnungswechsels erfassen.");
      return;
    }
    setMessage(`Zuordnung gespeichert: ${assignment}. Datenqualität: ${effect.quality}. Workflow-fähig: ${effect.workflow ? "Ja" : "Nein"}. Änderung wird auditierbar protokolliert.`);
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 800, borderRadius: 8, overflow: "hidden" }}>
      <div style={{ background: "#1a1a18", padding: "10px 20px", fontSize: 13, display: "flex", alignItems: "center", gap: 16 }}>
        <span style={{ fontWeight: 700, color: "#fff" }}>DiveLogix360</span>
        <span style={{ color: "#5F5E5A" }}>|</span>
        <span style={{ color: "#888780" }}>Tenant-Portal</span>
        <div style={{ marginLeft: "auto", display: "flex", gap: 16, fontSize: 12 }}>
          <span style={{ color: "#fff", fontWeight: 500, borderBottom: "1px solid #185FA5", paddingBottom: 2 }}>Equipment</span>
          <span style={{ color: "#888780" }}>Kunden</span>
          <span style={{ color: "#888780" }}>Workflows</span>
          <span style={{ color: "#D3D1C7", fontWeight: 500 }}>TSH · MA</span>
        </div>
      </div>

      <div style={{ padding: "18px 24px" }}>
        <div style={{ fontSize: 12, color: "#888780", marginBottom: 12 }}>
          <span style={{ color: "#185FA5" }}>Equipment</span><span style={{ margin: "0 6px" }}>›</span><span style={{ color: "#185FA5" }}>12l Stahlflasche gelb</span><span style={{ margin: "0 6px" }}>›</span><span>Zuordnung wechseln</span>
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h1 style={{ margin: 0, fontSize: 20, fontWeight: 500, color: "#1a1a18" }}>Kunde zuordnen / wechseln</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>EQ-05</span>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setMessage("Zurück zu EQ-03 ohne Änderung.")} style={secondaryButton}>Abbrechen</button>
            <button onClick={save} style={primaryButton}>Zuordnung speichern</button>
          </div>
        </div>

        <Card title="Equipment">
          <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: "#1a1a18" }}>12l Stahlflasche gelb</div>
              <div style={{ fontSize: 12, color: "#888780", marginTop: 4 }}>Tauchflasche · SN 123456 · INV INT-0047 · Lager A / Regal 2</div>
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <Pill bg="#E6F1FB" color="#185FA5">Aktuell</Pill>
              <Pill bg="#EEEDFE" color="#534AB7">Kunde: Max Muster</Pill>
            </div>
          </div>
        </Card>

        <Card title="1 · Neue Zuordnung wählen">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
            {[
              ["internal", "Intern", "Tenant / Tauchschule", "Schul- oder Verleihbestand"],
              ["customer", "Kunde", "Kundenequipment", "Kunde muss ausgewählt werden"],
              ["unassigned", "Unbestimmt", "Zuordnung später klären", "ggf. nicht workflow-fähig"],
            ].map(([value, title, sub, hint]) => (
              <button key={value} onClick={() => setAssignment(value)} style={{ padding: 14, minHeight: 82, borderRadius: 8, border: assignment === value ? "1.5px solid #185FA5" : "1px solid #D3D1C7", background: assignment === value ? "#E6F1FB" : "#fff", color: assignment === value ? "#185FA5" : "#5F5E5A", cursor: "pointer", textAlign: "left" }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{title}</div>
                <div style={{ fontSize: 11, marginTop: 6 }}>{sub}</div>
                <div style={{ fontSize: 10, marginTop: 6, opacity: 0.8 }}>{hint}</div>
              </button>
            ))}
          </div>
        </Card>

        {assignment === "customer" && (
          <Card title="2 · Kunde suchen" action={<button onClick={() => setMessage("Absprung zur Kundenanlage") } style={outlineButton}>+ Neuer Kunde</button>}>
            <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Kunde suchen: Name, E-Mail, Kundennummer..." style={fieldStyle} />
            <div style={{ marginTop: 12, display: "grid", gap: 8 }}>
              {filteredCustomers.map((customer) => (
                <button key={customer.id} onClick={() => setSelectedCustomerId(customer.id)} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", textAlign: "left", padding: "10px 12px", borderRadius: 6, border: selectedCustomerId === customer.id ? "1.5px solid #185FA5" : "1px solid #D3D1C7", background: selectedCustomerId === customer.id ? "#E6F1FB" : "#fff", cursor: "pointer" }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: "#1a1a18" }}>{customer.name}</div>
                    <div style={{ fontSize: 11, color: "#888780", marginTop: 2 }}>{customer.email}</div>
                  </div>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <Pill bg={customer.type === "Mitarbeiter" ? "#FAEEDA" : "#EEEDFE"} color={customer.type === "Mitarbeiter" ? "#BA7517" : "#534AB7"}>{customer.type}</Pill>
                    {selectedCustomerId === customer.id && <Pill bg="#185FA5" color="#fff">Ausgewählt</Pill>}
                  </div>
                </button>
              ))}
            </div>
          </Card>
        )}

        <Card title="3 · Auswirkung auf Datenqualität & Workflows">
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
            <Pill bg={effect.quality === "complete" ? "#EAF3DE" : effect.quality === "needs_review" ? "#FCEBEB" : "#FAEEDA"} color={effect.quality === "complete" ? "#3B6D11" : effect.quality === "needs_review" ? "#A32D2D" : "#BA7517"}>data_quality_status: {effect.quality}</Pill>
            <Pill bg={effect.workflow ? "#EAF3DE" : "#FCEBEB"} color={effect.workflow ? "#3B6D11" : "#A32D2D"}>Workflow-fähig: {effect.workflow ? "Ja" : "Nein"}</Pill>
            <Pill bg="#EAF3DE" color="#3B6D11">sync_status: synced</Pill>
          </div>
          <div style={{ fontSize: 12, color: "#5F5E5A" }}>{effect.hint}</div>
        </Card>

        <Card title="4 · Änderungsnotiz">
          <textarea value={changeNote} onChange={(e) => setChangeNote(e.target.value)} rows={4} placeholder="Warum wird die Zuordnung geändert?" style={{ ...fieldStyle, resize: "vertical" }} />
          <div style={{ marginTop: 8, fontSize: 11, color: "#888780" }}>Empfohlen bei jedem Zuordnungswechsel, besonders von/zu Kunde.</div>
        </Card>

        {message && <div style={{ padding: "10px 14px", background: message.includes("fehlt") || message.includes("empfohlen") ? "#FAEEDA" : "#EAF3DE", border: message.includes("fehlt") || message.includes("empfohlen") ? "1px solid #FAC775" : "1px solid #A8D08D", borderRadius: 8, fontSize: 12, color: message.includes("fehlt") || message.includes("empfohlen") ? "#BA7517" : "#3B6D11", marginBottom: 12 }}>{message}</div>}

        <div style={{ padding: "10px 14px", background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, fontSize: 11, color: "#BA7517" }}>
          <strong>Wireframe-Simulation:</strong> Die Zuordnung beeinflusst Datenqualität und Workflow-Fähigkeit. Mitarbeiter-Equipment wird über Kundendatensatz mit besonderem Merkmal abgebildet.
        </div>
      </div>
    </div>
  );
}

const fieldStyle = { width: "100%", boxSizing: "border-box", padding: "8px 10px", fontSize: 12, border: "1px solid #B4B2A9", borderRadius: 6, background: "#fff" };
const primaryButton = { padding: "8px 14px", fontSize: 12, background: "#185FA5", border: "none", borderRadius: 6, color: "#fff", cursor: "pointer", fontWeight: 600 };
const outlineButton = { padding: "7px 12px", fontSize: 12, background: "#fff", border: "1px solid #185FA5", borderRadius: 6, color: "#185FA5", cursor: "pointer", fontWeight: 600 };
const secondaryButton = { padding: "8px 14px", fontSize: 12, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 6, color: "#5F5E5A", cursor: "pointer" };
