import { createResource, For, Show } from 'solid-js';
import { FolderOpen } from 'lucide-solid';
import DashboardWidget from './DashboardWidget';
import type { RoleKey } from '../RoleDashboardShared';
import { PROFESSIONAL_ROLE_SET, ROLE_PREFIXES } from '../RoleDashboardShared';
import { fetchPortfolio } from '~/lib/api';

type Props = {
  roleKey: RoleKey;
};

async function fetchPortfolioData(roleKey: RoleKey) {
  if (PROFESSIONAL_ROLE_SET.has(roleKey)) {
    const prefix = ROLE_PREFIXES[roleKey];
    if (!prefix) return null;
    const data = await fetchPortfolio(prefix);
    return { items: Array.isArray(data) ? data : (data?.data || []), total: Array.isArray(data) ? data.length : (data?.data?.length || 0) };
  }
  return null;
}

function PortfolioStatRow(props: { label: string; value: number | string; color?: string }) {
  return (
    <div
      style={{
        display: 'flex',
        'align-items': 'center',
        'justify-content': 'space-between',
        padding: '6px 0',
        'border-bottom': '1px solid #F9FAFB',
      }}
    >
      <span style={{ 'font-size': '12px', color: '#6B7280' }}>{props.label}</span>
      <span
        style={{
          'font-size': '15px',
          'font-weight': '800',
          color: props.color || '#111827',
        }}
      >
        {props.value}
      </span>
    </div>
  );
}

export default function PortfolioWidget(props: Props) {
  const [data] = createResource(() => props.roleKey, fetchPortfolioData);

  const total = () => {
    const d = data();
    if (!d) return 0;
    return typeof d.total === 'number' ? d.total : (Array.isArray(d.items) ? d.items.length : 0);
  };

  return (
    <DashboardWidget
      title="Portfolio"
      loading={data.loading}
      error={data.error ? 'Failed to load' : undefined}
      icon={<FolderOpen size={16} />}
    >
      <Show when={!data.loading && !data.error}>
        <For each={[
          ['Portfolio Items', total(), '#374151'],
        ]}>
          {([label, value, color]) => <PortfolioStatRow label={label as string} value={String(value)} color={color as string} />}
        </For>
      </Show>
    </DashboardWidget>
  );
}
