import { useState } from "react";
import api from "../../../api/client";
import { FLOW_LABELS, PAYMENT_TYPE_LABELS, CATEGORY_LABELS } from "./shared";

const labelStyle = { fontSize: 11, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4 };
const inputStyle = { backgroundColor: "var(--bg-input)", color: "var(--text-primary)", border: "1px solid var(--border-primary)", borderRadius: 6, padding: "6px 10px", fontSize: 13, width: "100%" };

function ModalShell({ title, onClose, children, saving, onConfirm, confirmLabel = "Confirm" }) {
  return (
    <div style={{ position: "fixed", inset: 0, backgroundColor: "rgba(0,0,0,0.6)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 1000 }}>
      <div style={{ backgroundColor: "var(--bg-card)", borderRadius: 12, padding: 24, width: "100%", maxWidth: 460, border: "1px solid var(--border-primary)" }}
        onKeyDown={(e) => e.key === "Escape" && onClose()}>
        <h3 style={{ fontSize: 15, fontWeight: 700, color: "var(--text-heading)", marginBottom: 18 }}>{title}</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {children}
        </div>
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
          <button type="button" onClick={onClose}
            style={{ fontSize: 13, padding: "6px 16px", borderRadius: 6, border: "1px solid var(--border-primary)", backgroundColor: "transparent", color: "var(--text-muted)", cursor: "pointer" }}>
            Cancel
          </button>
          <button type="button" onClick={onConfirm} disabled={saving}
            style={{ fontSize: 13, fontWeight: 600, padding: "6px 18px", borderRadius: 6, border: "none", backgroundColor: "var(--btn-primary)", color: "#fff", cursor: "pointer", opacity: saving ? 0.6 : 1 }}>
            {saving ? "Saving..." : confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Init Negotiations Modal ────────────────────────────────────────────────────

export function InitNegotiationsModal({ customerId, user, onClose, onSuccess }) {
  const [form, setForm] = useState({
    date: new Date().toISOString().slice(0, 16),
    title: "",
    note: "",
  });
  const [saving, setSaving] = useState(false);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleConfirm = async () => {
    if (!form.title.trim()) { alert("Title is required."); return; }
    setSaving(true);
    try {
      await api.post(`/crm/customers/${customerId}/orders/init-negotiations`, {
        title: form.title.trim(),
        note: form.note.trim(),
        date: form.date ? new Date(form.date).toISOString() : new Date().toISOString(),
        created_by: user?.name || "Staff",
      });
      // Auto-set customer to Active when a new order is initiated
      try {
        await api.patch(`/crm/customers/${customerId}/relationship-status`, { status: "active" });
      } catch { /* non-critical */ }
      onSuccess();
      onClose();
    } catch (err) {
      alert(err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <ModalShell title="Init Negotiations" onClose={onClose} saving={saving} onConfirm={handleConfirm} confirmLabel="Create Order">
      <div>
        <div style={labelStyle}>Date</div>
        <input type="datetime-local" value={form.date} onChange={(e) => set("date", e.target.value)} style={inputStyle} />
      </div>
      <div>
        <div style={labelStyle}>Title <span style={{ color: "var(--danger)" }}>*</span></div>
        <input type="text" value={form.title} onChange={(e) => set("title", e.target.value)} style={inputStyle} placeholder="e.g. 3x Wall Mount Units — Athens Office" autoFocus />
      </div>
      <div>
        <div style={labelStyle}>Note (optional)</div>
        <textarea rows={3} value={form.note} onChange={(e) => set("note", e.target.value)} style={{ ...inputStyle, resize: "vertical" }} placeholder="Initial note or context..." />
      </div>
    </ModalShell>
  );
}

// ── Record Issue / Support Modal ──────────────────────────────────────────────

export function RecordIssueModal({ customerId, user, onClose, onSuccess }) {
  const [type, setType] = useState("issue"); // "issue" | "support"
  const [form, setForm] = useState({
    date: new Date().toISOString().slice(0, 16),
    note: "",
  });
  const [saving, setSaving] = useState(false);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleConfirm = async () => {
    if (!form.note.trim()) { alert("Note is required."); return; }
    setSaving(true);
    const endpoint = type === "issue" ? "technical-issues" : "install-support";
    try {
      await api.post(`/crm/customers/${customerId}/${endpoint}`, {
        note: form.note.trim(),
        opened_by: user?.name || "Staff",
        date: form.date ? new Date(form.date).toISOString() : new Date().toISOString(),
      });
      onSuccess();
      onClose();
    } catch (err) {
      alert(err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <ModalShell title="Record Issue / Support" onClose={onClose} saving={saving} onConfirm={handleConfirm} confirmLabel="Submit">
      {/* Type toggle */}
      <div style={{ display: "flex", gap: 0, borderRadius: 8, overflow: "hidden", border: "1px solid var(--border-primary)" }}>
        {[["issue", "Technical Issue"], ["support", "Install Support"]].map(([v, l]) => (
          <button
            key={v}
            type="button"
            onClick={() => setType(v)}
            style={{
              flex: 1, padding: "8px 0", fontSize: 13, fontWeight: 600, cursor: "pointer", border: "none",
              backgroundColor: type === v ? (v === "issue" ? "var(--crm-issue-active-bg)" : "var(--crm-support-active-bg)") : "transparent",
              color: type === v ? (v === "issue" ? "var(--crm-issue-active-text)" : "var(--crm-support-active-text)") : "var(--text-muted)",
              transition: "all 0.15s",
            }}
          >
            {l}
          </button>
        ))}
      </div>
      <div>
        <div style={labelStyle}>Date</div>
        <input type="datetime-local" value={form.date} onChange={(e) => set("date", e.target.value)} style={inputStyle} />
      </div>
      <div>
        <div style={labelStyle}>Note <span style={{ color: "var(--danger)" }}>*</span></div>
        <textarea rows={3} value={form.note} onChange={(e) => set("note", e.target.value)} style={{ ...inputStyle, resize: "vertical" }} placeholder="Describe the issue or support request..." autoFocus />
      </div>
    </ModalShell>
  );
}

// ── Record Payment Modal ──────────────────────────────────────────────────────

export function RecordPaymentModal({ customerId, user, orders, onClose, onSuccess }) {
  const [form, setForm] = useState({
    date: new Date().toISOString().slice(0, 16),
    flow: "payment",
    payment_type: "cash",
    category: "full_payment",
    amount: "",
    currency: "EUR",
    invoice_ref: "",
    order_ref: "",
    recorded_by: user?.name || "",
    note: "",
  });
  const [saving, setSaving] = useState(false);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleConfirm = async () => {
    if (!form.amount) { alert("Amount is required."); return; }
    setSaving(true);
    try {
      await api.post(`/crm/customers/${customerId}/transactions`, {
        ...form,
        amount: parseFloat(form.amount) || 0,
        date: form.date ? new Date(form.date).toISOString() : new Date().toISOString(),
        invoice_ref: form.invoice_ref || null,
        order_ref: form.order_ref || null,
        payment_type: form.flow === "invoice" ? null : (form.payment_type || null),
        note: form.note || "",
      });
      onSuccess();
      onClose();
    } catch (err) {
      alert(err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <ModalShell title="Record Payment" onClose={onClose} saving={saving} onConfirm={handleConfirm} confirmLabel="Record">
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <div>
          <div style={labelStyle}>Date</div>
          <input type="datetime-local" value={form.date} onChange={(e) => set("date", e.target.value)} style={inputStyle} />
        </div>
        <div>
          <div style={labelStyle}>Flow</div>
          <select value={form.flow} onChange={(e) => set("flow", e.target.value)} style={inputStyle}>
            {Object.entries(FLOW_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </select>
        </div>
        {form.flow !== "invoice" && (
          <div>
            <div style={labelStyle}>Payment Type</div>
            <select value={form.payment_type || ""} onChange={(e) => set("payment_type", e.target.value)} style={inputStyle}>
              {Object.entries(PAYMENT_TYPE_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
            </select>
          </div>
        )}
        <div>
          <div style={labelStyle}>Category</div>
          <select value={form.category} onChange={(e) => set("category", e.target.value)} style={inputStyle}>
            {Object.entries(CATEGORY_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </select>
        </div>
        <div>
          <div style={labelStyle}>Amount <span style={{ color: "var(--danger)" }}>*</span></div>
          <input type="number" min="0" step="0.01" value={form.amount} onChange={(e) => set("amount", e.target.value)} style={inputStyle} placeholder="0.00" autoFocus />
        </div>
        <div>
          <div style={labelStyle}>Currency</div>
          <select value={form.currency} onChange={(e) => set("currency", e.target.value)} style={inputStyle}>
            {["EUR", "USD", "GBP"].map((c) => <option key={c} value={c}>{c}</option>)}
          </select>
        </div>
        <div>
          <div style={labelStyle}>Invoice Ref</div>
          <input type="text" value={form.invoice_ref} onChange={(e) => set("invoice_ref", e.target.value)} style={inputStyle} placeholder="e.g. INV-2026-001" />
        </div>
        <div>
          <div style={labelStyle}>Order Ref</div>
          <select value={form.order_ref} onChange={(e) => set("order_ref", e.target.value)} style={inputStyle}>
            <option value="">— None —</option>
            {(orders || []).map((o) => (
              <option key={o.id} value={o.id}>{o.order_number || o.id.slice(0, 8)}{o.title ? ` — ${o.title}` : ""}</option>
            ))}
          </select>
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <div style={labelStyle}>Note</div>
          <textarea rows={2} value={form.note} onChange={(e) => set("note", e.target.value)} style={{ ...inputStyle, resize: "vertical" }} />
        </div>
      </div>
    </ModalShell>
  );
}
