import { For, Show, createSignal, onMount } from 'solid-js';
import { BTN_GHOST, BTN_ORANGE, CARD, INPUT, LABEL } from '~/components/DashboardShell';

const API = '/api/gateway';

type RequirementItem = {
  id: string;
  title: string;
  status?: string;
};

type LeadRequestItem = {
  id: string;
  professional_id?: string;
  status?: string;
  message?: string | null;
  created_at?: string;
};

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

type Props = {
  mode: 'received' | 'shortlisted';
};

export default function CustomerResponsesPage(props: Props) {
  const [requirements, setRequirements] = createSignal<RequirementItem[]>([]);
  const [selectedRequirementId, setSelectedRequirementId] = createSignal('');
  const [rows, setRows] = createSignal<LeadRequestItem[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [loadingRows, setLoadingRows] = createSignal(false);
  const [busyId, setBusyId] = createSignal<string | null>(null);
  const [msg, setMsg] = createSignal('');
  const [err, setErr] = createSignal('');

  const loadRequirements = async () => {
    setLoading(true);
    try {
      const res = await apiFetch('/api/customers/requirements?page=1&limit=100');
      const payload = await res.json().catch(() => ({}));
      const list = Array.isArray(payload?.data) ? payload.data : [];
      setRequirements(list);
      if (list.length > 0) {
        const first = selectedRequirementId() || list[0].id;
        setSelectedRequirementId(first);
        await loadResponses(first);
      } else {
        setSelectedRequirementId('');
        setRows([]);
      }
    } catch {
      setErr('Failed to load requirements.');
    } finally {
      setLoading(false);
    }
  };

  const loadResponses = async (requirementId: string) => {
    if (!requirementId) {
      setRows([]);
      return;
    }
    setLoadingRows(true);
    setErr('');
    try {
      const res = await apiFetch(`/api/customers/requirements/${requirementId}/requests`);
      const payload = await res.json().catch(() => ({}));
      if (!res.ok) {
        setRows([]);
        setErr(payload.error || payload.message || 'Failed to load responses.');
        return;
      }
      const list = Array.isArray(payload?.data) ? payload.data : [];
      setRows(list);
    } catch {
      setErr('Network error while loading responses.');
    } finally {
      setLoadingRows(false);
    }
  };

  onMount(loadRequirements);

  const runDecision = async (leadId: string, approve: boolean) => {
    if (!selectedRequirementId()) return;
    setBusyId(leadId);
    setMsg('');
    setErr('');
    try {
      const path = approve
        ? `/api/customers/requirements/${selectedRequirementId()}/requests/${leadId}/approve`
        : `/api/customers/requirements/${selectedRequirementId()}/requests/${leadId}/reject`;
      const res = await apiFetch(path, { method: 'POST' });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || 'Failed to update response.');
        return;
      }
      setMsg(approve ? 'Response moved to shortlisted.' : 'Response rejected.');
      await loadResponses(selectedRequirementId());
    } catch {
      setErr('Network error while updating response.');
    } finally {
      setBusyId(null);
    }
  };

  const filteredRows = () => {
    if (props.mode === 'shortlisted') {
      return rows().filter((row) => {
        const status = String(row.status || '').toUpperCase();
        return status === 'APPROVED' || status === 'SHORTLISTED';
      });
    }
    return rows();
  };

  return (
    <div style={{ display: 'grid', gap: '14px', 'max-width': '980px' }}>
      <div style={CARD}>
        <p style={{ margin: '0', 'font-size': '18px', 'font-weight': '800', color: '#111827' }}>
          {props.mode === 'shortlisted' ? 'Shortlisted Responses' : 'Received Responses'}
        </p>
        <p style={{ margin: '4px 0 0', 'font-size': '13px', color: '#6B7280' }}>
          {props.mode === 'shortlisted'
            ? 'Review approved responses from your requirements.'
            : 'Review incoming responses and shortlist the right professionals.'}
        </p>
      </div>

      <Show when={msg()}>
        <div style={{ ...CARD, border: '1px solid #BBF7D0', background: '#ECFDF5', padding: '12px 14px', color: '#065F46', 'font-size': '13px', 'font-weight': '600' }}>{msg()}</div>
      </Show>
      <Show when={err()}>
        <div style={{ ...CARD, border: '1px solid #FECACA', background: '#FEF2F2', padding: '12px 14px', color: '#B91C1C', 'font-size': '13px', 'font-weight': '600' }}>{err()}</div>
      </Show>

      <div style={CARD}>
        <div style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'flex-end', gap: '10px', 'flex-wrap': 'wrap' }}>
          <div style={{ 'min-width': '300px', flex: '1' }}>
            <label style={LABEL}>Select Requirement</label>
            <select
              value={selectedRequirementId()}
              onChange={(e) => {
                const next = e.currentTarget.value;
                setSelectedRequirementId(next);
                loadResponses(next);
              }}
              style={INPUT}
            >
              <Show when={requirements().length === 0}>
                <option value="">No requirements</option>
              </Show>
              <For each={requirements()}>
                {(item) => (
                  <option value={item.id}>
                    {item.title} ({String(item.status || 'DRAFT').replace(/_/g, ' ')})
                  </option>
                )}
              </For>
            </select>
          </div>
          <button type="button" onClick={() => loadResponses(selectedRequirementId())} style={BTN_GHOST}>Refresh</button>
        </div>
      </div>

      <Show when={loading()}>
        <div style={{ ...CARD, 'text-align': 'center', color: '#9CA3AF' }}>Loading requirements...</div>
      </Show>
      <Show when={!loading() && !selectedRequirementId()}>
        <div style={{ ...CARD, 'text-align': 'center', color: '#6B7280' }}>Post a requirement first to view responses.</div>
      </Show>
      <Show when={loadingRows()}>
        <div style={{ ...CARD, 'text-align': 'center', color: '#9CA3AF' }}>Loading responses...</div>
      </Show>
      <Show when={!loadingRows() && selectedRequirementId() && filteredRows().length === 0}>
        <div style={{ ...CARD, 'text-align': 'center', color: '#6B7280' }}>No responses found.</div>
      </Show>

      <Show when={!loadingRows() && filteredRows().length > 0}>
        <div style={{ display: 'grid', gap: '10px' }}>
          <For each={filteredRows()}>
            {(row) => (
              <div style={{ ...CARD, padding: '14px' }}>
                <div style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'flex-start', gap: '10px', 'flex-wrap': 'wrap' }}>
                  <div>
                    <p style={{ margin: '0', 'font-size': '14px', 'font-weight': '800', color: '#111827' }}>
                      Response #{row.id.slice(0, 8)}
                    </p>
                    <p style={{ margin: '4px 0 0', 'font-size': '12px', color: '#6B7280' }}>
                      Professional: {row.professional_id || '—'} {row.created_at ? `• ${new Date(row.created_at).toLocaleString('en-IN')}` : ''}
                    </p>
                  </div>
                  <span style={{ display: 'inline-flex', height: '24px', 'align-items': 'center', padding: '0 10px', 'border-radius': '999px', background: '#EEF2FF', color: '#3730A3', 'font-size': '11px', 'font-weight': '700' }}>
                    {String(row.status || 'NEW').replace(/_/g, ' ')}
                  </span>
                </div>
                <p style={{ margin: '8px 0 0', 'font-size': '13px', color: '#374151' }}>{row.message || 'No message added by professional.'}</p>
                <Show when={props.mode === 'received'}>
                  <div style={{ display: 'flex', gap: '8px', 'justify-content': 'flex-end', 'margin-top': '10px' }}>
                    <button type="button" onClick={() => runDecision(row.id, false)} disabled={busyId() === row.id} style={{ ...BTN_GHOST, height: '32px', 'font-size': '12px', padding: '0 12px', opacity: busyId() === row.id ? '0.7' : '1' }}>
                      Reject
                    </button>
                    <button type="button" onClick={() => runDecision(row.id, true)} disabled={busyId() === row.id} style={{ ...BTN_ORANGE, height: '32px', 'font-size': '12px', padding: '0 12px', opacity: busyId() === row.id ? '0.7' : '1' }}>
                      Shortlist
                    </button>
                  </div>
                </Show>
              </div>
            )}
          </For>
        </div>
      </Show>
    </div>
  );
}

