// Form modal: create / edit / delete tasks and events.

function Field({ label, children, hint }) {
  return (
    <div className="col gap-2">
      <div className="tiny">{label}</div>
      {children}
      {hint && <div className="small muted">{hint}</div>}
    </div>
  );
}

function inputStyle() {
  return {
    width: "100%", padding: "12px 14px",
    background: "var(--surface)", border: "1px solid var(--line-2)",
    borderRadius: 12, fontSize: 16, color: "var(--ink)", outline: "none",
  };
}

function Segmented({ options, value, onChange, color = "var(--terracotta)" }) {
  return (
    <div className="segmented" style={{
      display: "flex", flexWrap: "wrap",
      background: "var(--bg-2)", border: "1px solid var(--line)",
      borderRadius: 12, padding: 4, gap: 3,
    }}>
      {options.map(opt => {
        const active = opt.value === value;
        return (
          <button key={opt.value} type="button" onClick={() => onChange(opt.value)} style={{
            flex: "1 1 auto",
            padding: "10px 10px", borderRadius: 9,
            background: active ? "var(--surface)" : "transparent",
            color: active ? (opt.color || color) : "var(--ink-3)",
            fontWeight: active ? 600 : 500, fontSize: 13,
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 5,
            boxShadow: active ? "var(--shadow-sm)" : "none",
            border: active && opt.color ? `1px solid ${opt.color}33` : "1px solid transparent",
            minHeight: 40,
            transition: "all .12s ease",
          }}>
            {opt.icon && <Icon name={opt.icon} size={13} />}
            <span className="seg-label">{opt.label}</span>
          </button>
        );
      })}
    </div>
  );
}

function CustomDateChips({ days, onChange }) {
  const [input, setInput] = React.useState(ymd(addDays(TODAY, 1)));
  const sorted = [...(days || [])].sort();
  return (
    <div className="col gap-2">
      <div className="row gap-2" style={{ flexWrap: "wrap" }}>
        {sorted.length === 0 && <span className="muted small">Aucune date — ajoutez-en ci-dessous.</span>}
        {sorted.map(d => (
          <span key={d} className="row gap-1" style={{
            padding: "4px 8px", background: "var(--terracotta-tint)",
            color: "var(--terracotta-2)", borderRadius: 6, fontSize: 12, fontWeight: 500,
          }}>
            {fmtShort(fromYmd(d))}
            <button type="button" onClick={() => onChange(sorted.filter(x => x !== d))} style={{ color: "inherit", opacity: 0.6 }}>
              <Icon name="cross" size={10} strokeWidth={2.4} />
            </button>
          </span>
        ))}
      </div>
      <div className="row gap-2">
        <input type="date" value={input} onChange={(e) => setInput(e.target.value)} style={{ ...inputStyle(), width: "auto" }} />
        <Button variant="soft" icon="plus" onClick={() => {
          if (!input) return;
          if (sorted.includes(input)) return;
          onChange([...sorted, input]);
        }}>Ajouter</Button>
      </div>
    </div>
  );
}

function TaskForm({ initial, onSave, onDelete, onClose }) {
  const blank = {
    id: "",
    kind: "task",
    title: "",
    date: ymd(TODAY),
    priority: "mid",
    status: "todo",
    recurrence: { kind: "none" },
    notify: false,
    notes: "",
    overrides: {},
    assignee: null,
  };
  const [draft, setDraft] = React.useState({ ...blank, ...initial });
  const isNew = !initial?.id;
  const set = (k, v) => setDraft(d => ({ ...d, [k]: v }));

  const submit = (e) => {
    e?.preventDefault?.();
    if (!draft.title.trim()) return;
    const id = draft.id || `i_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;
    onSave({ ...draft, id });
    onClose();
  };

  return (
    <form onSubmit={submit} className="col">
      <div className="form-header row gap-3" style={{ padding: "18px 20px", borderBottom: "1px solid var(--line)", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div className="col gap-1">
          <div className="tiny">{isNew ? "Création" : "Modification"}</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 24 }}>
            {isNew ? "Nouvelle entrée" : draft.title || "Sans titre"}
          </div>
        </div>
        <IconButton icon="close" label="Fermer" onClick={onClose} />
      </div>

      <div className="form-body col gap-4" style={{ padding: 20 }}>
        <Field label="Type">
          <Segmented
            value={draft.kind}
            onChange={(v) => set("kind", v)}
            options={[
              { value: "task",        label: "Tâche",        icon: "check",        color: KINDS.task.color },
              { value: "appointment", label: "Rendez-vous",  icon: "stethoscope",  color: KINDS.appointment.color },
              { value: "birthday",    label: "Anniversaire", icon: "cake",         color: KINDS.birthday.color },
              { value: "family",      label: "Famille",      icon: "users",        color: KINDS.family.color },
              { value: "event",       label: "Événement",    icon: "party",        color: KINDS.event.color },
            ]}
          />
        </Field>

        <Field label="Titre">
          <input
            autoFocus
            placeholder={draft.kind === "task" ? "Ex: Sortir les poubelles" : "Ex: RDV chez le dentiste"}
            value={draft.title}
            onChange={(e) => set("title", e.target.value)}
            style={inputStyle()}
          />
        </Field>

        <div className="form-date-priority row gap-4">
          <div className="col gap-2 grow">
            <Field label="Date">
              <input type="date" value={draft.date} onChange={(e) => set("date", e.target.value)} style={inputStyle()} />
            </Field>
          </div>
          <div className="col gap-2 grow">
            <Field label="Priorité">
              <Segmented
                value={draft.priority}
                onChange={(v) => set("priority", v)}
                options={[
                  { value: "low",  label: "Faible",  icon: "flag", color: PRIORITIES.low.color  },
                  { value: "mid",  label: "Moyenne", icon: "flag", color: PRIORITIES.mid.color  },
                  { value: "high", label: "Élevée",  icon: "flag", color: PRIORITIES.high.color },
                ]}
              />
            </Field>
          </div>
        </div>

        {draft.kind === "task" && (draft.recurrence?.kind || "none") === "none" && !isNew && (
          <Field label="État">
            <Segmented
              value={draft.status}
              onChange={(v) => set("status", v)}
              options={Object.entries(STATES).map(([k, s]) => ({ value: k, label: s.label, color: s.color }))}
            />
          </Field>
        )}

        <Field label="Récurrence">
          <Segmented
            value={draft.recurrence?.kind || "none"}
            onChange={(v) => set("recurrence", { ...(draft.recurrence || {}), kind: v, days: v === "custom" ? (draft.recurrence?.days || []) : undefined })}
            options={[
              { value: "none",    label: "Une fois",    icon: "dot"    },
              { value: "daily",   label: "Quotidien",   icon: "sun"    },
              { value: "weekly",  label: "Hebdo",       icon: "calendar"},
              { value: "monthly", label: "Mensuel",     icon: "moon"   },
              { value: "yearly",  label: "Annuel",      icon: "star"   },
              { value: "custom",  label: "Sur mesure",  icon: "sparkle"},
            ]}
          />
        </Field>

        {draft.recurrence?.kind === "custom" && (
          <Field label="Dates personnalisées" hint="Choisissez chaque jour où la tâche doit apparaître.">
            <CustomDateChips
              days={draft.recurrence.days || []}
              onChange={(days) => set("recurrence", { ...draft.recurrence, days })}
            />
          </Field>
        )}

        <Field label="Assigné à">
          <Segmented
            value={draft.assignee || "both"}
            onChange={(v) => set("assignee", v === "both" ? null : v)}
            options={[
              { value: "both",     label: "Les deux", icon: "users"  },
              { value: "baptiste", label: "Baptiste",  icon: "dot"    },
              { value: "imelda",   label: "Imelda",    icon: "dot"    },
            ]}
          />
        </Field>

        <Field label="Notes">
          <textarea
            value={draft.notes}
            onChange={(e) => set("notes", e.target.value)}
            placeholder="Détails, lieu, horaire…"
            rows={3}
            style={{ ...inputStyle(), resize: "vertical", minHeight: 64 }}
          />
        </Field>

        <label className="row gap-3" style={{
          padding: "12px 14px", background: "var(--bg-2)",
          border: "1px solid var(--line)", borderRadius: 12,
          cursor: "pointer",
        }}>
          <div style={{
            width: 36, height: 20, borderRadius: 999,
            background: draft.notify ? "var(--terracotta)" : "var(--line-2)",
            position: "relative", transition: "all .15s ease",
          }}>
            <span style={{
              position: "absolute", top: 2, left: draft.notify ? 18 : 2,
              width: 16, height: 16, borderRadius: 999,
              background: "#FFF8F0", transition: "all .15s ease", boxShadow: "var(--shadow-sm)",
            }} />
          </div>
          <input type="checkbox" checked={draft.notify} onChange={(e) => set("notify", e.target.checked)} style={{ display: "none" }} />
          <div className="col grow" style={{ gap: 2 }}>
            <div style={{ fontWeight: 500 }}>Activer un rappel</div>
            <div className="small muted">Recevez une notification le jour-J</div>
          </div>
          <Icon name="bell" size={16} color="var(--ink-3)" />
        </label>
      </div>

      <div className="form-footer row gap-2" style={{ padding: "14px 20px", borderTop: "1px solid var(--line)", background: "var(--bg)" }}>
        {!isNew && (
          <Button variant="danger" icon="trash" type="button"
            onClick={() => { if (confirm(`Supprimer "${draft.title}" ?`)) { onDelete(draft.id); onClose(); } }}
          >Supprimer</Button>
        )}
        <div className="grow" />
        <Button variant="ghost" type="button" onClick={onClose}>Annuler</Button>
        <Button variant="primary" type="submit" icon="check">{isNew ? "Créer" : "Enregistrer"}</Button>
      </div>
    </form>
  );
}

Object.assign(window, { TaskForm });
