import { permissions } from "@mrp/shared";
import type { CrmRecordDetailDto } from "@mrp/shared/dist/crm/types.js";
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";

import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
import { CrmStatusBadge } from "./CrmStatusBadge";
import { type CrmEntity, crmConfigs } from "./config";

interface CrmDetailPageProps {
  entity: CrmEntity;
}

export function CrmDetailPage({ entity }: CrmDetailPageProps) {
  const { token, user } = useAuth();
  const { customerId, vendorId } = useParams();
  const recordId = entity === "customer" ? customerId : vendorId;
  const config = crmConfigs[entity];
  const [record, setRecord] = useState<CrmRecordDetailDto | null>(null);
  const [status, setStatus] = useState(`Loading ${config.singularLabel.toLowerCase()}...`);

  const canManage = user?.permissions.includes(permissions.crmWrite) ?? false;

  useEffect(() => {
    if (!token || !recordId) {
      return;
    }

    const loadRecord = entity === "customer" ? api.getCustomer(token, recordId) : api.getVendor(token, recordId);

    loadRecord
      .then((nextRecord) => {
        setRecord(nextRecord);
        setStatus(`${config.singularLabel} record loaded.`);
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : `Unable to load ${config.singularLabel.toLowerCase()}.`;
        setStatus(message);
      });
  }, [config.singularLabel, entity, recordId, token]);

  if (!record) {
    return <div className="rounded-[28px] border border-line/70 bg-surface/90 p-8 text-sm text-muted shadow-panel">{status}</div>;
  }

  return (
    <section className="space-y-6">
      <div className="rounded-[28px] border border-line/70 bg-surface/90 p-8 shadow-panel">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">CRM Detail</p>
            <h3 className="mt-3 text-3xl font-bold text-text">{record.name}</h3>
            <div className="mt-4">
              <CrmStatusBadge status={record.status} />
            </div>
            <p className="mt-2 text-sm text-muted">
              {config.singularLabel} record last updated {new Date(record.updatedAt).toLocaleString()}.
            </p>
          </div>
          <div className="flex flex-wrap gap-3">
            <Link
              to={config.routeBase}
              className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-4 py-3 text-sm font-semibold text-text"
            >
              Back to {config.collectionLabel.toLowerCase()}
            </Link>
            {canManage ? (
              <Link
                to={`${config.routeBase}/${record.id}/edit`}
                className="inline-flex items-center justify-center rounded-2xl bg-brand px-5 py-3 text-sm font-semibold text-white"
              >
                Edit {config.singularLabel.toLowerCase()}
              </Link>
            ) : null}
          </div>
        </div>
      </div>
      <div className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
        <article className="rounded-[28px] border border-line/70 bg-surface/90 p-8 shadow-panel">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Contact</p>
          <dl className="mt-6 grid gap-5 md:grid-cols-2">
            <div>
              <dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Email</dt>
              <dd className="mt-2 text-base text-text">{record.email}</dd>
            </div>
            <div>
              <dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Phone</dt>
              <dd className="mt-2 text-base text-text">{record.phone}</dd>
            </div>
            <div className="md:col-span-2">
              <dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Address</dt>
              <dd className="mt-2 whitespace-pre-line text-base text-text">
                {[record.addressLine1, record.addressLine2, `${record.city}, ${record.state} ${record.postalCode}`, record.country]
                  .filter(Boolean)
                  .join("\n")}
              </dd>
            </div>
          </dl>
        </article>
        <article className="rounded-[28px] border border-line/70 bg-surface/90 p-8 shadow-panel">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Notes</p>
          <p className="mt-4 whitespace-pre-line text-sm leading-7 text-text">
            {record.notes || "No internal notes recorded for this account yet."}
          </p>
          <div className="mt-8 rounded-2xl border border-line/70 bg-page/70 px-4 py-4 text-sm text-muted">
            Created {new Date(record.createdAt).toLocaleDateString()}
          </div>
        </article>
      </div>
    </section>
  );
}
