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

import OmsorgCard from "../../components/OmsorgCard";
import OmsorgBadge from "../../components/ui/OmsorgBadge";
import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";
import EmployeeTabs from "./EmployeeTabs";
import EditEmployeeDialog from "./EditEmployeeDialog";
import ContractsList from "./ContractsList";
import DocumentsList from "./DocumentsList";

function getInitials(firstName = "", lastName = "") {
  return `${firstName[0] ?? ""}${lastName[0] ?? ""}`.toUpperCase();
}

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

function formatAddress(employee) {
  const line = [employee.postalCode, employee.city].filter(Boolean).join(" ");
  const parts = [employee.street, line].filter(Boolean);

  if (employee.country && employee.country !== "Deutschland") {
    parts.push(employee.country);
  }

  return parts.length > 0 ? parts.join(", ") : "—";
}

export default function EmployeeDetailPanel({ employee, onUpdated }) {
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("Employees", "Edit");
  const canDelete = hasPermission("Employees", "Delete");
  const canViewDocuments = hasPermission("Documents", "View");
  const [activeTab, setActiveTab] = useState("overview");
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  useEffect(() => {
    setActiveTab("overview");
  }, [employee?.id]);

  async function handleDelete() {
    if (!window.confirm(`${employee.firstName} ${employee.lastName} wirklich löschen?`)) {
      return;
    }

    setIsDeleting(true);
    const result = await window.omsorg.employees.delete(employee.id);
    setIsDeleting(false);

    if (result.ok) {
      onUpdated?.(null);
    }
  }

  if (!employee) {
    return (
      <OmsorgCard>
        <div className="employee-detail-empty">
          <h2>Keine Personalakte ausgewählt</h2>
          <p>Wähle links einen Mitarbeiter aus.</p>
        </div>
      </OmsorgCard>
    );
  }

  const renderTabContent = () => {
    switch (activeTab) {
      case "documents":
        return <DocumentsList employeeId={employee.id} />;

      case "contracts":
        return <ContractsList employeeId={employee.id} />;

      case "assignments":
        return (
          <div className="employee-tab-content">
            <h3>Einsätze</h3>
            <p>
              Hier wird später die komplette
              Einsatzhistorie angezeigt.
            </p>
          </div>
        );

      case "overview":
      default:
        return (
          <div className="employee-detail-grid">
            <div>
              <strong>Telefon</strong>
              <p>{employee.phoneNumber ?? "—"}</p>
            </div>

            <div>
              <strong>E-Mail</strong>
              <p>{employee.email ?? "—"}</p>
            </div>

            <div>
              <strong>Adresse</strong>
              <p>{formatAddress(employee)}</p>
            </div>

            <div>
              <strong>Geburtsdatum</strong>
              <p>{formatDate(employee.dateOfBirth)}</p>
            </div>

            <div>
              <strong>Eintritt</strong>
              <p>{formatDate(employee.entryDate)}</p>
            </div>

            <div>
              <strong>Austritt</strong>
              <p>{formatDate(employee.exitDate)}</p>
            </div>

            <div>
              <strong>Beschäftigungsart</strong>
              <p>{employee.employmentType ?? "—"}</p>
            </div>

            <div>
              <strong>Qualifikation</strong>
              <p>{employee.qualification ?? "—"}</p>
            </div>

            <div>
              <strong>Notfallkontakt</strong>
              <p>
                {employee.emergencyContactName
                  ? `${employee.emergencyContactName}${
                      employee.emergencyContactRelation ? ` (${employee.emergencyContactRelation})` : ""
                    }${employee.emergencyContactPhone ? ` — ${employee.emergencyContactPhone}` : ""}`
                  : "—"}
              </p>
            </div>
          </div>
        );
    }
  };

  return (
    <OmsorgCard>
      <div className="employee-detail">
        <div className="employee-detail-header">
          <div className="employee-detail-avatar">
            {getInitials(employee.firstName, employee.lastName)}
          </div>

          <div>
            <h2>{`${employee.firstName} ${employee.lastName}`.trim()}</h2>
            <OmsorgBadge status={employee.status?.toLowerCase()} />
          </div>

          {canEdit && (
            <OmsorgButton variant="secondary" icon={Pencil} onClick={() => setIsEditDialogOpen(true)}>
              Bearbeiten
            </OmsorgButton>
          )}

          {canDelete && (
            <OmsorgButton variant="secondary" icon={Trash2} onClick={handleDelete} disabled={isDeleting}>
              Löschen
            </OmsorgButton>
          )}
        </div>

        <EmployeeTabs
          activeTab={activeTab}
          onChange={setActiveTab}
          hiddenTabIds={canViewDocuments ? [] : ["documents"]}
        />

        {renderTabContent()}
      </div>

      {isEditDialogOpen && (
        <EditEmployeeDialog
          employee={employee}
          onClose={() => setIsEditDialogOpen(false)}
          onUpdated={(updatedEmployee) => {
            setIsEditDialogOpen(false);
            onUpdated?.(updatedEmployee);
          }}
        />
      )}
    </OmsorgCard>
  );
}
