import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { FolderKanban, Receipt, ShoppingCart, Truck, AlertCircle } from 'lucide-react';
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';

// Customer-friendly production status wording — internal codes are not exposed.
const friendlyStatus = (s) => ({
  'Awaiting measurements': 'Getting your measurements',
  'Awaiting customer clarification': 'We need some details from you',
  'Designs awaiting selection': 'Designs ready for your review',
  'Awaiting workshop review': 'In workshop review',
  'Ready for design': 'Preparing your design',
  'Complete': 'Complete',
  'Archived': 'Archived',
}[s] || s);

export default function CustomerPortal() {
  const { account } = useAccount();
  const [data, setData] = useState(null);

  useEffect(() => {
    if (!account?.customer_uuid) { setData({}); return; }
    (async () => {
      const [projects, quotes, orders, covers] = await Promise.all([
        adapters.database.filter('CoverProject', { customer_uuid: account.customer_uuid }),
        adapters.database.filter('Quote', { customer_uuid: account.customer_uuid }),
        adapters.database.filter('Order', { customer_uuid: account.customer_uuid }),
        adapters.database.filter('CompletedCover', { customer_uuid: account.customer_uuid }),
      ]);
      setData({ projects, quotes, orders, covers });
    })();
  }, [account]);

  if (!account) return <LoadingPanel label="Loading your portal" />;
  if (!data) return <LoadingPanel label="Loading your records" />;

  if (!account.customer_uuid) return (
    <div className="panel mx-auto mt-12 max-w-lg p-8 text-center">
      <AlertCircle className="mx-auto h-10 w-10 text-amber-400" />
      <h2 className="mt-4 text-lg font-semibold text-white">No customer profile linked</h2>
      <p className="mt-2 text-sm text-shire-text-secondary">Your account is not yet linked to a customer record. Please contact SHiRE to complete setup.</p>
    </div>
  );

  const infoNeeded = data.projects.filter(p => p.status === 'Awaiting customer clarification');
  const designsReady = data.projects.filter(p => p.status === 'Designs awaiting selection');

  return (
    <>
      <PageHeader eyebrow="Customer Portal" title={`Welcome, ${account.preferred_name || account.display_name}`}
        description="Your cover requests, designs, quotes and orders — in your own words." />

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <div className="panel p-5"><FolderKanban className="h-6 w-6 text-violet-300" /><p className="mt-2 text-2xl font-bold text-white">{data.projects.length}</p><p className="text-xs text-shire-text-muted">Cover Requests</p></div>
        <div className="panel p-5"><AlertCircle className="h-6 w-6 text-amber-300" /><p className="mt-2 text-2xl font-bold text-white">{infoNeeded.length}</p><p className="text-xs text-shire-text-muted">Info Needed</p></div>
        <div className="panel p-5"><Receipt className="h-6 w-6 text-violet-300" /><p className="mt-2 text-2xl font-bold text-white">{data.quotes.length}</p><p className="text-xs text-shire-text-muted">Quotes</p></div>
        <div className="panel p-5"><ShoppingCart className="h-6 w-6 text-emerald-300" /><p className="mt-2 text-2xl font-bold text-white">{data.covers.length}</p><p className="text-xs text-shire-text-muted">Completed Covers</p></div>
      </div>

      <section className="panel mt-6 p-5">
        <h2 className="section-title">My Cover Requests</h2>
        {data.projects.length === 0 ? <p className="text-sm text-shire-text-muted">You have no cover requests yet. <Link to="/design-your-cover" className="text-violet-300 hover:underline">Start one here.</Link></p> : (
          <div className="space-y-2">
            {data.projects.map(p => (
              <Link key={p.uuid} to={`/portal/projects/${p.uuid}`} className="flex items-center justify-between rounded-xl border border-shire-border bg-shire-raised px-4 py-3 hover:border-shire-purple/40">
                <div><div className="text-sm font-medium text-slate-200">Request {p.project_id}</div>
                  {p.status === 'Awaiting customer clarification' && <div className="text-xs text-amber-300">Action needed — please provide the requested details.</div>}
                </div>
                <StatusPill tone={p.status === 'Complete' ? 'green' : p.status === 'Awaiting customer clarification' ? 'amber' : 'cyan'}>{friendlyStatus(p.status)}</StatusPill>
              </Link>
            ))}
          </div>
        )}
      </section>

      {data.quotes.length > 0 && (
        <section className="panel mt-6 p-5">
          <h2 className="section-title">Quotes</h2>
          <div className="space-y-2">{data.quotes.map(q => (
            <div key={q.uuid} className="flex items-center justify-between rounded-xl border border-shire-border bg-shire-raised px-4 py-3 text-sm">
              <span className="text-slate-200">{q.quote_number}</span>
              <StatusPill tone={q.approval_status === 'Approved' ? 'green' : 'amber'}>{q.approval_status}</StatusPill>
            </div>
          ))}</div>
        </section>
      )}

      {data.covers.length > 0 && (
        <section className="panel mt-6 p-5">
          <h2 className="section-title">Completed Covers</h2>
          <div className="space-y-2">{data.covers.map(c => (
            <div key={c.uuid} className="flex items-center justify-between rounded-xl border border-shire-border bg-shire-raised px-4 py-3 text-sm">
              <span className="text-slate-200">{c.cover_reference}</span>
              <span className="text-xs text-shire-text-muted">{c.completion_date}</span>
            </div>
          ))}</div>
        </section>
      )}
    </>
  );
}