import { createResource, For, Show } from 'solid-js';
import { MapPin } from 'lucide-solid';
import DashboardWidget from './DashboardWidget';
import type { RoleKey } from '../RoleDashboardShared';
import { PROFESSIONAL_ROLE_SET, ROLE_PREFIXES } from '../RoleDashboardShared';

const API = '';

async function apiFetch(path: string, opts?: RequestInit) {
  const token =
    typeof window !== 'undefined'
      ? window.sessionStorage.getItem('nxtgauge_access_token') || ''
      : '';
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts?.headers ?? {}),
    },
  });
}

type Props = {
  roleKey: RoleKey;
};

async function fetchLeadsData(roleKey: RoleKey) {
  if (PROFESSIONAL_ROLE_SET.has(roleKey)) {
    const prefix = ROLE_PREFIXES[roleKey];
    const res = await apiFetch(`/api/${prefix}/leads/requests/me?page=1&limit=100`);
    if (!res.ok) return null;
    const json = await res.json();
    return Array.isArray(json?.data) ? json.data : [];
  }
  if (roleKey === 'CUSTOMER') {
    const res = await apiFetch(`/api/customers/requirements?page=1&limit=100`);
    if (!res.ok) return null;
    const json = await res.json();
    return Array.isArray(json?.data) ? json.data : [];
  }
  return null;
}

function LeadStatRow(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 LeadsWidget(props: Props) {
  const [data, { refetch }] = createResource(() => props.roleKey, fetchLeadsData);

  const isProfessional = () => PROFESSIONAL_ROLE_SET.has(props.roleKey);
  const isCustomer = () => props.roleKey === 'CUSTOMER';

  const stats = () => {
    const items = data() || [];
    if (isProfessional()) {
      const pending = items.filter(
        (r: any) => String(r.status || '').toUpperCase() === 'PENDING'
      ).length;
      const accepted = items.filter((r: any) =>
        ['APPROVED', 'CONTACT_UNLOCKED'].includes(String(r.status || '').toUpperCase())
      ).length;
      const rejected = items.filter(
        (r: any) => String(r.status || '').toUpperCase() === 'REJECTED'
      ).length;
      return { total: items.length, pending, accepted, rejected };
    }
    if (isCustomer()) {
      const total = items.length;
      const open = items.filter(
        (r: any) => String(r.status || '').toUpperCase() === 'OPEN'
      ).length;
      const closed = items.filter(
        (r: any) => String(r.status || '').toUpperCase() === 'CLOSED'
      ).length;
      const pending = items.filter((r: any) =>
        String(r.status || '').toUpperCase().includes('PENDING')
      ).length;
      return { total, open, closed, pending };
    }
    return null;
  };

  return (
    <DashboardWidget
      title={isProfessional() ? 'My Lead Requests' : 'My Requirements'}
      loading={data.loading}
      error={data.error ? 'Service unavailable' : undefined}
      icon={<MapPin size={16} />}
    >
      <Show when={stats()}>
        <For each={isProfessional() ? [
          ['Total Requests', stats()!.total, '#374151'],
          ['Pending', stats()!.pending, '#D97706'],
          ['Accepted', stats()!.accepted, '#059669'],
          ['Rejected', stats()!.rejected, '#DC2626'],
        ] : [
          ['Total Requirements', stats()!.total, '#374151'],
          ['Open', stats()!.open, '#059669'],
          ['In Verification', stats()!.pending, '#D97706'],
          ['Closed', stats()!.closed, '#6B7280'],
        ]}>
          {([label, value, color]) => <LeadStatRow label={label} value={value} color={color} />}
        </For>
      </Show>
    </DashboardWidget>
  );
}
