import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import PageHeader from '@/components/workshop/PageHeader';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import StatusPill from '@/components/workshop/StatusPill';
import { useAccount } from '@/lib/AccountContext';
import { adapters } from '@/services/serviceConfig';

const CONFIG = {
  requests: { title: 'My Cover Requests', entity: 'CoverProject', link: (r) => `/portal/projects/${r.uuid}`, label: (r) => r.project_id, status: (r) => r.status },
  quotes: { title: 'My Quotes', entity: 'Quote', link: (r) => `/portal/quotes/${r.uuid}`, label: (r) => r.quote_number, status: (r) => r.approval_status },
  orders: { title: 'My Orders', entity: 'Order', link: (r) => `/portal/orders/${r.uuid}`, label: (r) => r.order_number, status: (r) => r.production_status },
  shipping: { title: 'Shipping', entity: 'Shipment', link: (r) => `/portal/completed-covers/${r.completed_cover_uuid}`, label: (r) => r.shipment_reference, status: (r) => r.status },
  'completed-covers': { title: 'Completed Covers', entity: 'CompletedCover', link: (r) => `/portal/completed-covers/${r.uuid}`, label: (r) => r.cover_reference, status: (r) => r.inspection_result },
};

export default function PortalSection({ section }) {
  const { account } = useAccount();
  const [items, setItems] = useState(null);
  const cfg = CONFIG[section];

  useEffect(() => {
    if (!account?.customer_uuid || !cfg) { setItems([]); return; }
    adapters.database.filter(cfg.entity, { customer_uuid: account.customer_uuid }).then(setItems);
  }, [account, section]);

  if (!cfg) return <LoadingPanel label="Loading" />;
  if (!items) return <LoadingPanel label={cfg.title} />;

  return (
    <>
      <PageHeader eyebrow="Customer Portal" title={cfg.title} description="Only your own records are shown." />
      {items.length === 0 ? <p className="text-sm text-shire-text-muted">No records yet.</p> : (
        <div className="space-y-2">
          {items.map(r => (
            <Link key={r.uuid} to={cfg.link(r)} className="panel flex items-center justify-between p-4 hover:border-shire-purple/40">
              <span className="text-sm font-medium text-slate-200">{cfg.label(r)}</span>
              <StatusPill tone="cyan">{cfg.status(r) || '—'}</StatusPill>
            </Link>
          ))}
        </div>
      )}
    </>
  );
}