import { useEffect, useMemo, useState } from "react";
import SectionCard from "../components/SectionCard";
import { api } from "../lib/api";

function emptyRoleForm() {
  return { code: "", name: "", description: "", is_active: true };
}

function emptyTeamRoleForm() {
  return {
    code: "",
    name: "",
    description: "",
    can_view_cases: false,
    can_write_cases: false,
    can_view_documents: false,
    can_write_documents: false,
    is_active: true,
  };
}

function toggleValue(list, value) {
  const set = new Set(list || []);
  if (set.has(value)) set.delete(value);
  else set.add(value);
  return Array.from(set);
}

export default function PermissionsPage() {
  const [data, setData] = useState({ pages: [], permissions: [], role_profiles: [], team_roles: [], users: [] });
  const [selectedRoleId, setSelectedRoleId] = useState("");
  const [roleDraft, setRoleDraft] = useState({ page_keys: [], permission_keys: [] });
  const [roleForm, setRoleForm] = useState(emptyRoleForm());
  const [teamRoleForm, setTeamRoleForm] = useState(emptyTeamRoleForm());
  const [selectedTeamRoleId, setSelectedTeamRoleId] = useState("");
  const [selectedUserId, setSelectedUserId] = useState("");
  const [userDraft, setUserDraft] = useState({ role_profile_ids: [], team_role_ids: [] });
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  async function load() {
    setError("");
    try {
      const matrix = await api.get("/permissions/matrix");
      setData(matrix || { pages: [], permissions: [], role_profiles: [], team_roles: [], users: [] });

      const firstRole = matrix?.role_profiles?.[0];
      if (!selectedRoleId && firstRole) {
        setSelectedRoleId(String(firstRole.id));
        setRoleDraft({ page_keys: firstRole.page_keys || [], permission_keys: firstRole.permission_keys || [] });
      }
    } catch (err) {
      setError(err.message || "Rechtematrix konnte nicht geladen werden.");
    }
  }

  useEffect(() => {
    load();
  }, []);

  const selectedRole = useMemo(
    () => data.role_profiles.find((item) => String(item.id) === String(selectedRoleId)),
    [data.role_profiles, selectedRoleId]
  );

  const selectedUser = useMemo(
    () => data.users.find((item) => String(item.id) === String(selectedUserId)),
    [data.users, selectedUserId]
  );

  const permissionsByCategory = useMemo(() => {
    const groups = new Map();
    for (const permission of data.permissions || []) {
      const key = permission.category || "Sonstige";
      if (!groups.has(key)) groups.set(key, []);
      groups.get(key).push(permission);
    }
    return Array.from(groups.entries());
  }, [data.permissions]);

  function selectRole(id) {
    const role = data.role_profiles.find((item) => String(item.id) === String(id));
    setSelectedRoleId(id);
    setRoleDraft({ page_keys: role?.page_keys || [], permission_keys: role?.permission_keys || [] });
    setMessage("");
    setError("");
  }

  function selectTeamRole(id) {
    const role = data.team_roles.find((item) => String(item.id) === String(id));
    setSelectedTeamRoleId(id);
    setTeamRoleForm(role ? { ...role } : emptyTeamRoleForm());
  }

  function selectUser(id) {
    const user = data.users.find((item) => String(item.id) === String(id));
    setSelectedUserId(id);
    setUserDraft({
      role_profile_ids: (user?.role_profile_ids || []).map(Number),
      team_role_ids: (user?.team_role_ids || []).map(Number),
    });
    setMessage("");
    setError("");
  }

  async function saveRoleMatrix() {
    if (!selectedRoleId) return;
    setError("");
    setMessage("");
    try {
      const matrix = await api.put(`/permissions/roles/${selectedRoleId}/matrix`, roleDraft);
      setData(matrix);
      setMessage("Rechtematrix gespeichert. Betroffene Benutzer sehen die Änderung spätestens nach Aktualisierung der Seite oder erneutem Login.");
    } catch (err) {
      setError(err.message || "Rechtematrix konnte nicht gespeichert werden.");
    }
  }

  async function createRole(e) {
    e.preventDefault();
    setError("");
    setMessage("");
    try {
      await api.post("/permissions/roles", roleForm);
      setRoleForm(emptyRoleForm());
      await load();
      setMessage("Neue Rolle erstellt.");
    } catch (err) {
      setError(err.message || "Rolle konnte nicht erstellt werden.");
    }
  }

  async function saveTeamRole(e) {
    e.preventDefault();
    setError("");
    setMessage("");
    try {
      if (selectedTeamRoleId) {
        await api.put(`/permissions/team-roles/${selectedTeamRoleId}`, teamRoleForm);
        setMessage("Teamrolle gespeichert.");
      } else {
        await api.post("/permissions/team-roles", teamRoleForm);
        setMessage("Teamrolle erstellt.");
      }
      setSelectedTeamRoleId("");
      setTeamRoleForm(emptyTeamRoleForm());
      await load();
    } catch (err) {
      setError(err.message || "Teamrolle konnte nicht gespeichert werden.");
    }
  }

  async function saveUserAssignments() {
    if (!selectedUserId) return;
    setError("");
    setMessage("");
    try {
      const matrix = await api.put(`/permissions/users/${selectedUserId}/assignments`, userDraft);
      setData(matrix);
      setMessage("Benutzer-Zuweisungen gespeichert.");
    } catch (err) {
      setError(err.message || "Zuweisungen konnten nicht gespeichert werden.");
    }
  }

  return (
    <>
      <style>{`
        .permissions-grid { display: grid; gap: 16px; }
        .permissions-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .permission-list { display: grid; gap: 8px; }
        .permission-check { display: flex; gap: 8px; align-items: flex-start; padding: 8px 10px; border: 1px solid rgba(148,163,184,.35); border-radius: 12px; }
        .permission-check small { display: block; opacity: .7; margin-top: 2px; }
        .role-list { display: flex; gap: 8px; flex-wrap: wrap; }
        .role-pill { border: 1px solid rgba(148,163,184,.45); background: rgba(255,255,255,.55); border-radius: 999px; padding: 8px 12px; cursor: pointer; }
        .role-pill.active { font-weight: 700; background: rgba(37,99,235,.12); color: #1d4ed8; }
        .mini-form { display: grid; gap: 10px; }
        @media (max-width: 980px) { .permissions-two-col { grid-template-columns: 1fr; } }
      `}</style>

      <div className="permissions-grid">
        {error ? <div className="alert error">{error}</div> : null}
        {message ? <div className="alert success">{message}</div> : null}

        <SectionCard
          title="Rechtematrix"
          subtitle="Seiten werden im Menü ausgeblendet, wenn keine zugewiesene Rolle die Seite freigibt. Custom-Rollen können zusätzliche Seiten und Rechte bekommen."
          actions={<button className="btn" type="button" disabled={!selectedRoleId} onClick={saveRoleMatrix}>Matrix speichern</button>}
        >
          <div className="role-list" style={{ marginBottom: 14 }}>
            {data.role_profiles.map((role) => (
              <button
                key={role.id}
                type="button"
                className={`role-pill ${String(role.id) === String(selectedRoleId) ? "active" : ""}`}
                onClick={() => selectRole(String(role.id))}
              >
                {role.name}{role.is_system ? " · System" : ""}
              </button>
            ))}
          </div>

          {selectedRole ? (
            <div className="permissions-two-col">
              <div>
                <h3>Webseiten</h3>
                <div className="permission-list">
                  {data.pages.map((page) => (
                    <label key={page.page_key} className="permission-check">
                      <input
                        type="checkbox"
                        checked={roleDraft.page_keys.includes(page.page_key)}
                        onChange={() => setRoleDraft((prev) => ({ ...prev, page_keys: toggleValue(prev.page_keys, page.page_key) }))}
                      />
                      <span><strong>{page.label}</strong><small>{page.path} · {page.description}</small></span>
                    </label>
                  ))}
                </div>
              </div>

              <div>
                <h3>Funktionsrechte</h3>
                {permissionsByCategory.map(([category, permissions]) => (
                  <div key={category} style={{ marginBottom: 14 }}>
                    <strong>{category}</strong>
                    <div className="permission-list" style={{ marginTop: 8 }}>
                      {permissions.map((permission) => (
                        <label key={permission.permission_key} className="permission-check">
                          <input
                            type="checkbox"
                            checked={roleDraft.permission_keys.includes(permission.permission_key)}
                            onChange={() => setRoleDraft((prev) => ({ ...prev, permission_keys: toggleValue(prev.permission_keys, permission.permission_key) }))}
                          />
                          <span><strong>{permission.label}</strong><small>{permission.permission_key} · {permission.description}</small></span>
                        </label>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : <div>Keine Rolle ausgewählt.</div>}
        </SectionCard>

        <div className="permissions-two-col">
          <SectionCard title="Neue Custom-Rolle" subtitle="Die Basisrolle am Benutzer bleibt bestehen; Custom-Rollen erweitern Seiten und Rechte.">
            <form className="mini-form" onSubmit={createRole}>
              <label><span>Code</span><input className="input" value={roleForm.code} onChange={(e) => setRoleForm({ ...roleForm, code: e.target.value })} placeholder="z.B. datenschutz_team" /></label>
              <label><span>Name</span><input className="input" value={roleForm.name} onChange={(e) => setRoleForm({ ...roleForm, name: e.target.value })} /></label>
              <label><span>Beschreibung</span><textarea className="input textarea" value={roleForm.description} onChange={(e) => setRoleForm({ ...roleForm, description: e.target.value })} /></label>
              <button className="btn" type="submit">Custom-Rolle erstellen</button>
            </form>
          </SectionCard>

          <SectionCard title="Teamrollen" subtitle="Teamrollen können Vorgänge und Dokumente sichtbar machen, ohne globale Systemrechte zu vergeben.">
            <form className="mini-form" onSubmit={saveTeamRole}>
              <label>
                <span>Vorhandene Teamrolle bearbeiten</span>
                <select className="input" value={selectedTeamRoleId} onChange={(e) => selectTeamRole(e.target.value)}>
                  <option value="">Neue Teamrolle</option>
                  {data.team_roles.map((role) => <option key={role.id} value={role.id}>{role.name}</option>)}
                </select>
              </label>
              <label><span>Code</span><input className="input" value={teamRoleForm.code} onChange={(e) => setTeamRoleForm({ ...teamRoleForm, code: e.target.value })} /></label>
              <label><span>Name</span><input className="input" value={teamRoleForm.name} onChange={(e) => setTeamRoleForm({ ...teamRoleForm, name: e.target.value })} /></label>
              <label><span>Beschreibung</span><textarea className="input textarea" value={teamRoleForm.description || ""} onChange={(e) => setTeamRoleForm({ ...teamRoleForm, description: e.target.value })} /></label>
              <label className="permission-check"><input type="checkbox" checked={teamRoleForm.can_view_cases} onChange={(e) => setTeamRoleForm({ ...teamRoleForm, can_view_cases: e.target.checked })} /> Vorgänge lesen</label>
              <label className="permission-check"><input type="checkbox" checked={teamRoleForm.can_write_cases} onChange={(e) => setTeamRoleForm({ ...teamRoleForm, can_write_cases: e.target.checked })} /> Vorgänge bearbeiten</label>
              <label className="permission-check"><input type="checkbox" checked={teamRoleForm.can_view_documents} onChange={(e) => setTeamRoleForm({ ...teamRoleForm, can_view_documents: e.target.checked })} /> Dokumente lesen</label>
              <label className="permission-check"><input type="checkbox" checked={teamRoleForm.can_write_documents} onChange={(e) => setTeamRoleForm({ ...teamRoleForm, can_write_documents: e.target.checked })} /> Dokumente bearbeiten</label>
              <button className="btn" type="submit">{selectedTeamRoleId ? "Teamrolle speichern" : "Teamrolle erstellen"}</button>
            </form>
          </SectionCard>
        </div>

        <SectionCard title="Benutzer-Zuweisungen" subtitle="Hier weist du Benutzern zusätzliche Custom-Rollen und Teamrollen zu.">
          <div className="permissions-two-col">
            <label>
              <span>Benutzer</span>
              <select className="input" value={selectedUserId} onChange={(e) => selectUser(e.target.value)}>
                <option value="">Bitte auswählen</option>
                {data.users.map((user) => <option key={user.id} value={user.id}>{user.full_name} · {user.email} · Basisrolle: {user.role}</option>)}
              </select>
            </label>
            <div style={{ display: "flex", alignItems: "end" }}>
              <button className="btn" type="button" disabled={!selectedUserId} onClick={saveUserAssignments}>Zuweisungen speichern</button>
            </div>
          </div>

          {selectedUser ? (
            <div className="permissions-two-col" style={{ marginTop: 16 }}>
              <div>
                <h3>Custom-Rollen</h3>
                <div className="permission-list">
                  {data.role_profiles.filter((role) => !role.is_system).map((role) => (
                    <label key={role.id} className="permission-check">
                      <input
                        type="checkbox"
                        checked={userDraft.role_profile_ids.includes(Number(role.id))}
                        onChange={() => setUserDraft((prev) => ({ ...prev, role_profile_ids: toggleValue(prev.role_profile_ids.map(Number), Number(role.id)) }))}
                      />
                      <span><strong>{role.name}</strong><small>{role.description}</small></span>
                    </label>
                  ))}
                  {data.role_profiles.filter((role) => !role.is_system).length === 0 ? <div className="helper-text">Noch keine Custom-Rollen vorhanden.</div> : null}
                </div>
              </div>

              <div>
                <h3>Teamrollen</h3>
                <div className="permission-list">
                  {data.team_roles.map((role) => (
                    <label key={role.id} className="permission-check">
                      <input
                        type="checkbox"
                        checked={userDraft.team_role_ids.includes(Number(role.id))}
                        onChange={() => setUserDraft((prev) => ({ ...prev, team_role_ids: toggleValue(prev.team_role_ids.map(Number), Number(role.id)) }))}
                      />
                      <span><strong>{role.name}</strong><small>{role.description}</small></span>
                    </label>
                  ))}
                  {data.team_roles.length === 0 ? <div className="helper-text">Noch keine Teamrollen vorhanden.</div> : null}
                </div>
              </div>
            </div>
          ) : null}
        </SectionCard>
      </div>
    </>
  );
}
