import { useMemo, useState } from "react";

const initialPositions = [
  {
    id: "eq-001",
    name: "12l Stahlflasche gelb",
    serial: "123456",
    inventory: "INT-0047",
    material: "Stahl",
    pressure: "232 bar",
    due: "2026-04-30",
    dueState: "overdue",
    status: "OK",
  },
  {
    id: "eq-002",
    name: "10l Aluflasche silber",
    serial: "AL-9001",
    inventory: "INT-0052",
    material: "Aluminium",
    pressure: "200 bar",
    due: "2026-05-20",
    dueState: "due",
    status: "OK",
  },
  {
    id: "eq-004",
    name: "7l Stage Stahl",
    serial: "STAGE-07",
    inventory: "INT-0074",
    material: "Stahl",
    pressure: "200 bar",
    due: "2026-05-25",
    dueState: "due",
    status: "OK",
  },
];

const providers = [
  "SVTI / Dienstleister Beispiel",
  "TÜV Süd Beispiel",
  "Prüfservice Muster",
  "Freitext verwenden",
];

const styles = {
  overdue: { bg: "#FCEBEB", color: "#A32D2D", label: "überfällig" },
  due: { bg: "#FAEEDA", color: "#BA7517", label: "fällig" },
  OK: { bg: "#EAF3DE", color: "#3B6D11", label: "OK" },
  draft: { bg: "#FAEEDA", color: "#BA7517", label: "draft" },
  submitted: { bg: "#EEEDFE", color: "#534AB7", label: "submitted" },
};

function Pill({ value, label }) {
  const s = styles[value] || { bg: "#F1EFE8", color: "#5F5E5A", label: value };
  return <span style={{ background: s.bg, color: s.color, borderRadius: 999, padding: "3px 9px", fontSize: 11, fontWeight: 600 }}>{label || s.label}</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 TUEV02PruefungEinreichen() {
  const [title, setTitle] = useState("TÜV Sammelprüfung Mai 2026");
  const [reference, setReference] = useState("");
  const [provider, setProvider] = useState("SVTI / Dienstleister Beispiel");
  const [providerText, setProviderText] = useState("");
  const [submittedAt, setSubmittedAt] = useState("2026-05-06");
  const [plannedReturn, setPlannedReturn] = useState("");
  const [deliveryMode, setDeliveryMode] = useState("Sammelabgabe");
  const [notes, setNotes] = useState("Flaschen gesammelt für externe Prüfung vorbereitet.");
  const [positions, setPositions] = useState(initialPositions);
  const [message, setMessage] = useState("");

  const effectiveProvider = provider === "Freitext verwenden" ? providerText.trim() : provider;

  const validation = useMemo(() => {
    const errors = [];
    if (positions.length === 0) errors.push("Mindestens eine Equipment-Position ist erforderlich.");
    if (!effectiveProvider) errors.push("Prüfstelle oder Freitext ist erforderlich.");
    if (!submittedAt) errors.push("Einreichdatum ist für Einreichen erforderlich.");
    return errors;
  }, [positions, effectiveProvider, submittedAt]);

  function removePosition(id) {
    setPositions((current) => current.filter((position) => position.id !== id));
  }

  function saveDraft() {
    if (positions.length === 0) {
      setMessage("Entwurf kann nicht gespeichert werden: Mindestens eine Position ist erforderlich.");
      return;
    }
    setMessage(`Entwurf gespeichert: ${positions.length} Position(en), Status draft. Workflow-Historie und Audit-Log werden vorbereitet.`);
  }

  function submit() {
    if (validation.length > 0) {
      setMessage(`Einreichen blockiert: ${validation.join(" ")}`);
      return;
    }
    setMessage(`Prüfauftrag eingereicht: ${positions.length} Position(en), Status submitted. Operative Nutzung wird für relevante Workflows gesperrt.`);
  }

  return (
    <div style={{ fontFamily: "var(--font-sans, system-ui)", background: "#F1EFE8", minHeight: 840, 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: "#888780" }}>Equipment</span>
          <span style={{ color: "#fff", fontWeight: 500, borderBottom: "1px solid #185FA5", paddingBottom: 2 }}>TÜV-Inspektion</span>
          <span style={{ color: "#888780" }}>Fristen</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" }}>TÜV-Inspektion</span><span style={{ margin: "0 6px" }}>›</span><span style={{ color: "#185FA5" }}>Prüffällige Equipment-Liste</span><span style={{ margin: "0 6px" }}>›</span><span>Prüfung einreichen</span>
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
            <h1 style={{ margin: 0, fontSize: 20, fontWeight: 500, color: "#1a1a18" }}>Prüfung einreichen</h1>
            <span style={{ background: "#E6F1FB", color: "#185FA5", borderRadius: 999, padding: "2px 8px", fontSize: 11, fontWeight: 600 }}>TÜV-02</span>
            <Pill value="draft" label={`${positions.length} Position(en)`} />
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setMessage("Zurück zu TÜV-01 ohne Speicherung.")} style={secondaryButton}>Abbrechen</button>
            <button onClick={saveDraft} style={outlineButton}>Entwurf speichern</button>
            <button onClick={submit} style={primaryButton}>Einreichen</button>
          </div>
        </div>

        <div style={{ padding: "10px 14px", background: "#E6F1FB", border: "1px solid #B5D4F4", borderRadius: 8, fontSize: 12, color: "#185FA5", marginBottom: 14 }}>
          Sammel-Prüfauftrag aus TÜV-01. Das spätere Prüfergebnis wird je Equipment-Position einzeln in TÜV-05 erfasst.
        </div>

        <Card title="1 · Prüfauftrag">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <Field label="Auftragstitel"><input value={title} onChange={(e) => setTitle(e.target.value)} style={fieldStyle} /></Field>
            <Field label="Interne Referenz"><input value={reference} onChange={(e) => setReference(e.target.value)} placeholder="optional" style={fieldStyle} /></Field>
          </div>
        </Card>

        <Card title="2 · Prüfstelle / Dienstleister">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <Field label="Prüfstelle *">
              <select value={provider} onChange={(e) => setProvider(e.target.value)} style={fieldStyle}>
                {providers.map((item) => <option key={item} value={item}>{item}</option>)}
              </select>
            </Field>
            <Field label="Freitext-Fallback">
              <input value={providerText} onChange={(e) => setProviderText(e.target.value)} placeholder="wenn nicht in Liste" disabled={provider !== "Freitext verwenden"} style={{ ...fieldStyle, background: provider === "Freitext verwenden" ? "#fff" : "#F1EFE8" }} />
            </Field>
          </div>
        </Card>

        <Card title="3 · Einreichung / Termine">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
            <Field label="Einreichdatum *"><input type="date" value={submittedAt} onChange={(e) => setSubmittedAt(e.target.value)} style={fieldStyle} /></Field>
            <Field label="Geplante Rückgabe"><input type="date" value={plannedReturn} onChange={(e) => setPlannedReturn(e.target.value)} style={fieldStyle} /></Field>
            <Field label="Abgabemodus"><select value={deliveryMode} onChange={(e) => setDeliveryMode(e.target.value)} style={fieldStyle}><option>Sammelabgabe</option><option>persönlich</option><option>Versand</option><option>intern organisiert</option></select></Field>
          </div>
        </Card>

        <Card title="4 · Equipment-Positionen" action={<span style={{ fontSize: 11, color: "#888780" }}>{positions.length} Position(en)</span>}>
          <div style={{ display: "grid", gap: 8 }}>
            {positions.map((position) => (
              <div key={position.id} style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 0.8fr 0.8fr", gap: 10, alignItems: "center", border: "1px solid #F1EFE8", borderRadius: 8, padding: "10px 12px" }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "#1a1a18" }}>{position.name}</div>
                  <div style={{ fontSize: 11, color: "#888780", marginTop: 3 }}>SN {position.serial} · INV {position.inventory}</div>
                  <div style={{ fontSize: 11, color: "#888780", marginTop: 3 }}>{position.material} · {position.pressure}</div>
                </div>
                <div>
                  <Pill value={position.dueState} />
                  <div style={{ fontSize: 11, color: "#888780", marginTop: 6 }}>{position.due}</div>
                </div>
                <div><Pill value="OK" /></div>
                <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                  <button onClick={() => removePosition(position.id)} style={miniButton}>Entfernen</button>
                  <button onClick={() => setMessage(`${position.name}: öffnet EQ-03.`)} style={miniButton}>EQ-03</button>
                </div>
              </div>
            ))}
            {positions.length === 0 && <div style={{ padding: 12, background: "#FAEEDA", border: "1px solid #FAC775", borderRadius: 8, color: "#BA7517", fontSize: 12 }}>Keine Positionen vorhanden. Einreichen ist blockiert.</div>}
          </div>
        </Card>

        <Card title="5 · Hinweise / Referenzen">
          <textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} placeholder="Bemerkung oder Übergabenotiz erfassen..." style={{ ...fieldStyle, resize: "vertical" }} />
        </Card>

        <Card title="6 · Prüf- und Sperrhinweise">
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 10 }}>
            <Pill value={validation.length === 0 ? "OK" : "overdue"} label={validation.length === 0 ? "einreichbar" : "blockiert"} />
            <Pill value="submitted" label="Status nach Einreichen: submitted" />
            <Pill value="draft" label="Entwurf möglich" />
          </div>
          <div style={{ fontSize: 12, color: validation.length === 0 ? "#3B6D11" : "#BA7517", lineHeight: 1.6 }}>
            {validation.length === 0 ? "Alle Positionen sind einreichbar. Beim Einreichen wird operative Nutzung für relevante Workflows gesperrt." : validation.join(" ")}
          </div>
        </Card>

        {message && <div style={{ padding: "10px 14px", background: message.includes("blockiert") || message.includes("nicht") ? "#FAEEDA" : "#EAF3DE", border: message.includes("blockiert") || message.includes("nicht") ? "1px solid #FAC775" : "1px solid #A8D08D", borderRadius: 8, fontSize: 12, color: message.includes("blockiert") || message.includes("nicht") ? "#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> Entfernen von Positionen, Freitext-Prüfstelle und leeres Einreichdatum beeinflussen die Validierung. Einreichen setzt den Auftrag auf submitted.
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return <label style={{ display: "block", fontSize: 12, fontWeight: 500, color: "#1a1a18" }}><span style={{ display: "block", marginBottom: 6 }}>{label}</span>{children}</label>;
}

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: "8px 14px", 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" };
const miniButton = { padding: "4px 8px", fontSize: 10, background: "#fff", border: "1px solid #B4B2A9", borderRadius: 4, color: "#5F5E5A", cursor: "pointer" };
