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

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

interface CrmListPageProps {
  entity: CrmEntity;
}

export function CrmListPage({ entity }: CrmListPageProps) {
  const { token, user } = useAuth();
  const config = crmConfigs[entity];
  const [records, setRecords] = useState<CrmRecordSummaryDto[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [stateFilter, setStateFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState<"ALL" | CrmRecordStatus>("ALL");
  const [status, setStatus] = useState(`Loading ${config.collectionLabel.toLowerCase()}...`);

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

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

    const filters = {
      q: searchTerm.trim() || undefined,
      state: stateFilter.trim() || undefined,
      status: statusFilter === "ALL" ? undefined : statusFilter,
    };

    const loadRecords = entity === "customer" ? api.getCustomers(token, filters) : api.getVendors(token, filters);

    loadRecords
      .then((nextRecords) => {
        setRecords(nextRecords);
        setStatus(`${nextRecords.length} ${config.collectionLabel.toLowerCase()} matched the current filters.`);
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : `Unable to load ${config.collectionLabel.toLowerCase()}.`;
        setStatus(message);
      });
  }, [config.collectionLabel, entity, searchTerm, stateFilter, statusFilter, token]);

  return (
    <section 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</p>
          <h3 className="mt-3 text-2xl font-bold text-text">{config.collectionLabel}</h3>
          <p className="mt-2 max-w-2xl text-sm text-muted">
            Operational contact records, shipping addresses, and account context for active {config.collectionLabel.toLowerCase()}.
          </p>
        </div>
        {canManage ? (
          <Link
            to={`${config.routeBase}/new`}
            className="inline-flex items-center justify-center rounded-2xl bg-brand px-5 py-3 text-sm font-semibold text-white"
          >
            New {config.singularLabel.toLowerCase()}
          </Link>
        ) : null}
      </div>
      <div className="mt-6 grid gap-4 rounded-3xl border border-line/70 bg-page/60 p-4 lg:grid-cols-[1.4fr_0.8fr_0.8fr]">
        <label className="block">
          <span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">Search</span>
          <input
            value={searchTerm}
            onChange={(event) => setSearchTerm(event.target.value)}
            placeholder={`Search ${config.collectionLabel.toLowerCase()} by company, email, phone, or location`}
            className="w-full rounded-2xl border border-line/70 bg-surface px-4 py-3 text-text outline-none transition focus:border-brand"
          />
        </label>
        <label className="block">
          <span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">Status</span>
          <select
            value={statusFilter}
            onChange={(event) => setStatusFilter(event.target.value as "ALL" | CrmRecordStatus)}
            className="w-full rounded-2xl border border-line/70 bg-surface px-4 py-3 text-text outline-none transition focus:border-brand"
          >
            {crmStatusFilters.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </label>
        <label className="block">
          <span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">State / Province</span>
          <input
            value={stateFilter}
            onChange={(event) => setStateFilter(event.target.value)}
            placeholder="Filter by region"
            className="w-full rounded-2xl border border-line/70 bg-surface px-4 py-3 text-text outline-none transition focus:border-brand"
          />
        </label>
      </div>
      <div className="mt-6 rounded-2xl border border-line/70 bg-page/60 px-4 py-3 text-sm text-muted">{status}</div>
      {records.length === 0 ? (
        <div className="mt-6 rounded-3xl border border-dashed border-line/70 bg-page/60 px-6 py-12 text-center text-sm text-muted">
          {config.emptyMessage}
        </div>
      ) : (
        <div className="mt-6 overflow-hidden rounded-2xl border border-line/70">
          <table className="min-w-full divide-y divide-line/70 text-sm">
            <thead className="bg-page/80 text-left text-muted">
              <tr>
                <th className="px-4 py-3">Name</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Email</th>
                <th className="px-4 py-3">Phone</th>
                <th className="px-4 py-3">Location</th>
                <th className="px-4 py-3">Updated</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-line/70 bg-surface">
              {records.map((record) => (
                <tr key={record.id} className="transition hover:bg-page/70">
                  <td className="px-4 py-3 font-semibold text-text">
                    <Link to={`${config.routeBase}/${record.id}`} className="hover:text-brand">
                      {record.name}
                    </Link>
                  </td>
                  <td className="px-4 py-3">
                    <CrmStatusBadge status={record.status} />
                  </td>
                  <td className="px-4 py-3 text-muted">{record.email}</td>
                  <td className="px-4 py-3 text-muted">{record.phone}</td>
                  <td className="px-4 py-3 text-muted">
                    {record.city}, {record.state}, {record.country}
                  </td>
                  <td className="px-4 py-3 text-muted">{new Date(record.updatedAt).toLocaleDateString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}
