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

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

type LeadRequestItem = {
  id: string;
  professional_id?: string;
  professional_name?: string | null;
  professional_avatar?: string | null;
  professional_role?: string | null;
  professional_bio?: string | null;
  professional_skills?: string[] | null;
  professional_location?: string | null;
  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") || ""
      : "";
  return fetch(path, {
    ...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/requests?lead_id=${requirementId}&page=1&limit=50`);
      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/requests/${leadId}/approve`
        : `/api/customers/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) => {
              const status = String(row.status || 'NEW').toUpperCase();
              const isDecided = status === 'APPROVED' || status === 'SHORTLISTED' || status === 'REJECTED';
              const skills = Array.isArray(row.professional_skills) ? row.professional_skills : [];

              return (
                <div style={{ ...CARD, padding: '16px' }}>
                  {/* Professional identity row */}
                  <div style={{ display: 'flex', 'align-items': 'flex-start', gap: '12px' }}>
                    {/* Avatar */}
                    <div style={{
                      width: '52px', height: '52px', 'border-radius': '50%', 'flex-shrink': 0,
                      background: '#F3F4F6', overflow: 'hidden',
                      display: 'flex', 'align-items': 'center', 'justify-content': 'center',
                      'font-size': '22px', border: '2px solid #E5E7EB',
                    }}>
                      {row.professional_avatar
                        ? <img src={row.professional_avatar} alt="" style={{ width: '100%', height: '100%', 'object-fit': 'cover' }} />
                        : '👤'}
                    </div>

                    {/* Name + role + location */}
                    <div style={{ flex: 1, 'min-width': 0 }}>
                      <div style={{ display: 'flex', 'align-items': 'center', gap: '8px', 'flex-wrap': 'wrap' }}>
                        <p style={{ margin: 0, 'font-size': '14px', 'font-weight': '800', color: '#111827' }}>
                          {row.professional_name || 'Professional'}
                        </p>
                        <span style={{
                          'font-size': '10px', 'font-weight': '700', padding: '2px 8px',
                          'border-radius': '999px',
                          background: status === 'APPROVED' || status === 'SHORTLISTED' ? '#DCFCE7' : status === 'REJECTED' ? '#FEE2E2' : '#EEF2FF',
                          color: status === 'APPROVED' || status === 'SHORTLISTED' ? '#15803D' : status === 'REJECTED' ? '#B91C1C' : '#3730A3',
                        }}>
                          {status.replace(/_/g, ' ')}
                        </span>
                      </div>
                      <Show when={row.professional_role}>
                        <p style={{ margin: '2px 0 0', 'font-size': '12px', color: '#6B7280', 'font-weight': '600' }}>
                          {String(row.professional_role).replace(/_/g, ' ')}
                        </p>
                      </Show>
                      <Show when={row.professional_location}>
                        <p style={{ margin: '1px 0 0', 'font-size': '11px', color: '#9CA3AF' }}>
                          📍 {row.professional_location}
                        </p>
                      </Show>
                    </div>

                    <p style={{ margin: 0, 'font-size': '11px', color: '#9CA3AF', 'flex-shrink': 0 }}>
                      {row.created_at ? new Date(row.created_at).toLocaleDateString('en-IN', { day: 'numeric', month: 'short' }) : ''}
                    </p>
                  </div>

                  {/* Bio */}
                  <Show when={row.professional_bio}>
                    <p style={{ margin: '10px 0 0', 'font-size': '13px', color: '#374151', 'line-height': '1.5' }}>
                      {row.professional_bio}
                    </p>
                  </Show>

                  {/* Skills */}
                  <Show when={skills.length > 0}>
                    <div style={{ display: 'flex', 'flex-wrap': 'wrap', gap: '5px', 'margin-top': '8px' }}>
                      <For each={skills.slice(0, 6)}>
                        {(skill) => (
                          <span style={{ 'font-size': '11px', 'font-weight': '600', padding: '2px 8px', 'border-radius': '10px', background: '#FFF7ED', color: '#C2410C' }}>
                            {skill}
                          </span>
                        )}
                      </For>
                      <Show when={skills.length > 6}>
                        <span style={{ 'font-size': '11px', color: '#9CA3AF' }}>+{skills.length - 6} more</span>
                      </Show>
                    </div>
                  </Show>

                  {/* Message from professional */}
                  <Show when={row.message}>
                    <div style={{ margin: '10px 0 0', padding: '10px 12px', background: '#F9FAFB', 'border-radius': '8px', 'border-left': '3px solid #E5E7EB' }}>
                      <p style={{ margin: 0, 'font-size': '12px', color: '#6B7280', 'font-weight': '700', 'margin-bottom': '4px' }}>Message</p>
                      <p style={{ margin: 0, 'font-size': '13px', color: '#374151' }}>{row.message}</p>
                    </div>
                  </Show>

                  {/* Actions */}
                  <Show when={props.mode === 'received' && !isDecided}>
                    <div style={{ display: 'flex', gap: '8px', 'justify-content': 'flex-end', 'margin-top': '12px' }}>
                      <button
                        type="button"
                        onClick={() => runDecision(row.id, false)}
                        disabled={busyId() === row.id}
                        style={{ ...BTN_GHOST, height: '32px', 'font-size': '12px', padding: '0 14px', 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 14px', opacity: busyId() === row.id ? '0.7' : '1' }}
                      >
                        Shortlist
                      </button>
                    </div>
                  </Show>
                  <Show when={props.mode === 'received' && isDecided}>
                    <p style={{ margin: '10px 0 0', 'font-size': '12px', color: '#9CA3AF', 'text-align': 'right' }}>
                      {status === 'REJECTED' ? 'You rejected this response.' : 'Shortlisted — contact will be shared.'}
                    </p>
                  </Show>
                </div>
              );
            }}
          </For>
        </div>
      </Show>
    </div>
  );
}

