import React, { useCallback, useEffect, useState } from 'react';
import { FaChevronDown, FaChevronUp, FaExternalLinkAlt } from 'react-icons/fa';

export interface ProjectSalesAndCustomerPanelProps {
  projectName?: string;
  isNew: boolean;
  customer?: string;
  customerName?: string;
  salesOrder?: string;
  prefillCustomer?: string;
  prefillSalesOrder?: string;
}

function ReadonlyLinkRow(props: { label: string; value: string; onOpen?: () => void }) {
  const { label, value, onOpen } = props;
  return (
    <div>
      <div className="text-[11px] font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">
        {label}
      </div>
      {value ? (
        <button
          type="button"
          onClick={onOpen}
          className="w-full text-left px-3 py-2 rounded-lg bg-gray-100 dark:bg-gray-700/50 text-sm text-gray-900 dark:text-white border border-transparent hover:border-blue-300 dark:hover:border-blue-600 transition-colors"
        >
          {value}
        </button>
      ) : (
        <div className="px-3 py-2 rounded-lg bg-gray-100 dark:bg-gray-700/40 text-sm text-gray-400 dark:text-gray-500 min-h-[40px] flex items-center">
          —
        </div>
      )}
    </div>
  );
}

const ProjectSalesAndCustomerPanel: React.FC<ProjectSalesAndCustomerPanelProps> = ({
  projectName,
  isNew,
  customer,
  customerName,
  salesOrder,
  prefillCustomer,
  prefillSalesOrder,
}) => {
  const [customerOpen, setCustomerOpen] = useState(true);
  const [soCount, setSoCount] = useState<number | null>(null);

  const cust = (customer || prefillCustomer || '').trim();
  const so = (salesOrder || prefillSalesOrder || '').trim();
  const custDisplay = (customerName || cust).trim();

  const loadSoCount = useCallback(async () => {
    if (!projectName || isNew) {
      setSoCount(0);
      return;
    }
    try {
      const filters = JSON.stringify([['Sales Order', 'project', '=', projectName]]);
      const q = new URLSearchParams();
      q.set('fields', JSON.stringify(['count(name) as count']));
      q.set('filters', filters);
      const r = await fetch(`/api/resource/Sales Order?${q}`, { credentials: 'include' });
      const body = await r.json().catch(() => ({}));
      const n = body?.data?.[0]?.count;
      setSoCount(typeof n === 'number' ? n : 0);
    } catch {
      setSoCount(0);
    }
  }, [projectName, isNew]);

  useEffect(() => {
    loadSoCount();
  }, [loadSoCount]);

  const canViewFilteredList = Boolean(projectName && !isNew);
  const countLabel = isNew ? '' : soCount === null ? ' (…)' : ` (${soCount})`;

  const openDesk = (path: string) => {
    window.open(`${window.location.origin}${path}`, '_blank', 'noopener,noreferrer');
  };

  return (
    <div className="space-y-4 mb-5">
      <div>
        <button
          type="button"
          disabled={!canViewFilteredList}
          onClick={() =>
            canViewFilteredList &&
            openDesk(
              `/app/sales-order/view/list?filters=${encodeURIComponent(JSON.stringify([['project', '=', projectName]]))}`
            )
          }
          className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-800 dark:text-gray-100 hover:bg-gray-50 dark:hover:bg-gray-700/80 disabled:opacity-45 disabled:cursor-not-allowed shadow-sm"
        >
          <FaExternalLinkAlt className="text-gray-500 dark:text-gray-400 shrink-0" size={14} />
          View sales orders{countLabel}
        </button>
      </div>

      <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/50 overflow-hidden">
        <button
          type="button"
          onClick={() => setCustomerOpen(v => !v)}
          className="w-full flex items-center justify-between px-4 py-3 text-left bg-teal-50 dark:bg-teal-950/30 border-b border-teal-100 dark:border-teal-900"
        >
          <span className="text-sm font-semibold text-teal-900 dark:text-teal-100">Customer details</span>
          {customerOpen ? <FaChevronUp className="text-teal-700" /> : <FaChevronDown className="text-teal-700" />}
        </button>
        {customerOpen && (
          <div className="p-4 grid grid-cols-1 sm:grid-cols-2 gap-4">
            <ReadonlyLinkRow
              label="Customer"
              value={custDisplay}
              onOpen={() => cust && openDesk(`/app/Form/Customer/${encodeURIComponent(cust)}`)}
            />
            <ReadonlyLinkRow
              label="Sales order"
              value={so}
              onOpen={() => so && openDesk(`/app/Form/Sales%20Order/${encodeURIComponent(so)}`)}
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default ProjectSalesAndCustomerPanel;
