import { useCallback, useEffect, useState } from "react";
import { Plus, Trash2 } from "lucide-react";

import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";
import CreateAssignmentDialog from "./CreateAssignmentDialog";

const CONFLICT_LABELS = {
  Qualification: "Qualifikation",
  Absence: "Abwesenheit",
  WorkingHours: "Arbeitszeit",
  Overlap: "Überschneidung",
  Contract: "Vertrag"
};

function formatDate(value) {
  if (!value) return "—";
  return new Date(value).toLocaleDateString("de-DE");
}

export default function AssignmentsList({ orderId, order, requiredHeadcount }) {
  const { hasPermission } = useAuth();
  const canCreate = hasPermission("Assignments", "Create");
  const canDelete = hasPermission("Assignments", "Delete");

  const [assignments, setAssignments] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [deletingId, setDeletingId] = useState(null);
  const [warnings, setWarnings] = useState([]);

  const loadAssignments = useCallback(async () => {
    setIsLoading(true);
    const result = await window.omsorg.assignments.list({ orderId, pageSize: 100 });
    if (result.ok) {
      setAssignments(result.data?.items ?? []);
    }
    setIsLoading(false);
  }, [orderId]);

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

  async function handleDeleteAssignment(assignmentId) {
    if (!window.confirm("Diese Zuweisung wirklich löschen?")) {
      return;
    }
    setDeletingId(assignmentId);
    const result = await window.omsorg.assignments.delete(assignmentId);
    setDeletingId(null);
    if (result.ok) {
      await loadAssignments();
    }
  }

  const formatDateRange = (startDate, endDate) => {
    if (startDate === endDate) {
      return formatDate(startDate);
    }
    return `${formatDate(startDate)} – ${formatDate(endDate)}`;
  };

  return (
    <div className="assignments-section">
      <div className="assignments-header">
        <div>
          <h3>Zuweisungen</h3>
          <p className="assignments-count">
            {assignments.length} / {requiredHeadcount} Mitarbeiter zugewiesen
          </p>
        </div>
        {canCreate && (
          <OmsorgButton variant="primary" size="sm" icon={Plus} onClick={() => setIsCreateDialogOpen(true)}>
            Zuweisung hinzufügen
          </OmsorgButton>
        )}
      </div>

      {warnings.length > 0 && (
        <div className="assignments-warnings">
          {warnings.map((w, i) => (
            <p key={i}>⚠ {CONFLICT_LABELS[w.type] ?? w.type}: {w.message}</p>
          ))}
        </div>
      )}

      {isLoading ? (
        <p>Lädt...</p>
      ) : assignments.length === 0 ? (
        <p className="assignments-empty">Noch keine Zuweisungen. {canCreate && "Klicke oben, um einen Mitarbeiter zuzuweisen."}</p>
      ) : (
        <div className="assignments-table">
          <div className="assignments-table-header">
            <div>Mitarbeiter</div>
            <div>Zeitraum</div>
            <div>Notiz</div>
            {canDelete && <div></div>}
          </div>
          {assignments.map((assignment) => (
            <div key={assignment.id} className="assignments-table-row">
              <div className="assignments-cell">
                {assignment.employeeFirstName} {assignment.employeeLastName}
              </div>
              <div className="assignments-cell">
                {formatDateRange(assignment.startDate, assignment.endDate)}
              </div>
              <div className="assignments-cell">{assignment.note ?? "—"}</div>
              {canDelete && (
                <div className="assignments-cell assignments-cell-action">
                  <button
                    className="assignments-delete-btn"
                    onClick={() => handleDeleteAssignment(assignment.id)}
                    disabled={deletingId === assignment.id}
                    title="Zuweisung löschen"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {isCreateDialogOpen && (
        <CreateAssignmentDialog
          orderId={orderId}
          order={order}
          onClose={() => setIsCreateDialogOpen(false)}
          onCreated={(conflicts) => {
            setIsCreateDialogOpen(false);
            setWarnings(conflicts ?? []);
            loadAssignments();
          }}
        />
      )}

      <style>{`
        .assignments-section {
          margin-top: 2rem;
          padding-top: 2rem;
          border-top: 1px solid var(--color-border);
        }

        .assignments-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 1rem;
        }

        .assignments-header h3 {
          margin: 0 0 0.25rem 0;
          font-size: 1.1rem;
        }

        .assignments-count {
          margin: 0;
          font-size: 0.9rem;
          color: var(--color-text-secondary);
        }

        .assignments-warnings {
          background-color: rgba(240, 195, 109, 0.12);
          border: 1px solid rgba(240, 195, 109, 0.45);
          color: #f0c36d;
          border-radius: 4px;
          padding: 0.75rem;
          margin-bottom: 1rem;
        }

        .assignments-warnings p {
          margin: 0.25rem 0;
          font-size: 0.9rem;
        }

        .assignments-empty {
          color: var(--color-text-secondary);
          font-style: italic;
          margin: 1rem 0 0 0;
        }

        .assignments-table {
          border: 1px solid var(--color-border);
          border-radius: 4px;
          overflow: hidden;
          margin-top: 1rem;
        }

        .assignments-table-header {
          display: grid;
          grid-template-columns: 1fr 1.5fr 1.5fr ${canDelete ? "40px" : ""};
          background-color: var(--color-bg-secondary);
          padding: 0.75rem;
          font-weight: 600;
          font-size: 0.9rem;
          gap: 1rem;
        }

        .assignments-table-row {
          display: grid;
          grid-template-columns: 1fr 1.5fr 1.5fr ${canDelete ? "40px" : ""};
          padding: 0.75rem;
          border-top: 1px solid var(--color-border);
          gap: 1rem;
          align-items: center;
        }

        .assignments-cell {
          font-size: 0.9rem;
        }

        .assignments-cell-action {
          display: flex;
          justify-content: center;
        }

        .assignments-delete-btn {
          background: none;
          border: none;
          color: var(--color-text-secondary);
          cursor: pointer;
          padding: 0.25rem;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 3px;
          transition: all 0.2s;
        }

        .assignments-delete-btn:hover:not(:disabled) {
          background-color: var(--color-bg-secondary);
          color: var(--color-error);
        }

        .assignments-delete-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      `}</style>
    </div>
  );
}
