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

const API = '';
const NAVY = '#0D0D2A';
const ORANGE = '#FF5E13';

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 ProfessionalType = {
  key: string;
  label: string;
  emoji: string;
  description: string;
  tags: string[];
};

const PROFESSIONAL_TYPES: ProfessionalType[] = [
  { key: 'PHOTOGRAPHER', label: 'Photographer', emoji: '📷', description: 'Wedding, portrait, event, and commercial photography.', tags: ['Wedding', 'Events', 'Portrait', 'Commercial'] },
  { key: 'MAKEUP_ARTIST', label: 'Makeup Artist', emoji: '💄', description: 'Bridal, editorial, and special occasion makeup.', tags: ['Bridal', 'Editorial', 'Events', 'Grooming'] },
  { key: 'TUTOR', label: 'Tutor', emoji: '📚', description: 'Academic tutoring, coaching, and test preparation.', tags: ['School', 'College', 'IIT-JEE', 'NEET', 'Languages'] },
  { key: 'FITNESS_TRAINER', label: 'Fitness Trainer', emoji: '💪', description: 'Personal training, yoga, CrossFit, and group classes.', tags: ['Personal Training', 'Yoga', 'CrossFit', 'Zumba'] },
  { key: 'CATERING_SERVICES', label: 'Catering Services', emoji: '🍽️', description: 'Home catering, event catering, and tiffin services.', tags: ['Events', 'Home Delivery', 'Tiffin', 'Corporate'] },
  { key: 'DEVELOPER', label: 'Developer', emoji: '💻', description: 'Web, mobile, and software development services.', tags: ['Web', 'Mobile', 'React', 'Flutter', 'Full Stack'] },
  { key: 'VIDEO_EDITOR', label: 'Video Editor', emoji: '🎬', description: 'Reels, short films, commercials, and YouTube content.', tags: ['Reels', 'YouTube', 'Wedding Films', 'Ads'] },
  { key: 'GRAPHIC_DESIGNER', label: 'Graphic Designer', emoji: '🎨', description: 'Logos, branding, social media, and print design.', tags: ['Logo', 'Branding', 'Social Media', 'Print'] },
  { key: 'SOCIAL_MEDIA_MANAGER', label: 'Social Media Manager', emoji: '📱', description: 'Content strategy, posting, and audience growth.', tags: ['Instagram', 'Facebook', 'LinkedIn', 'Content'] },
  { key: 'UGC_CONTENT_CREATOR', label: 'UGC Creator', emoji: '🎥', description: 'User-generated content for brands and products.', tags: ['UGC', 'Brand Content', 'Product Videos', 'Reviews'] },
];

export default function CustomerBrowseProfessionalsPage() {
  const [selected, setSelected] = createSignal<ProfessionalType | null>(null);
  const [showForm, setShowForm] = createSignal(false);
  const [saving, setSaving] = createSignal(false);
  const [msg, setMsg] = createSignal('');
  const [err, setErr] = createSignal('');
  const [form, setForm] = createSignal({
    title: '',
    description: '',
    budget_min: '',
    budget_max: '',
    location: '',
    area: '',
    tags: '',
  });

  const openEnquiry = (type: ProfessionalType) => {
    setSelected(type);
    setForm({
      title: `Looking for a ${type.label}`,
      description: '',
      budget_min: '',
      budget_max: '',
      location: '',
      area: '',
      tags: type.tags.join(', '),
    });
    setMsg('');
    setErr('');
    setShowForm(true);
  };

  const closeForm = () => {
    setShowForm(false);
    setSelected(null);
  };

  const submitEnquiry = async () => {
    const f = form();
    if (!f.title.trim()) { setErr('Title is required.'); return; }
    if (!f.description.trim()) { setErr('Please describe what you need.'); return; }

    setSaving(true);
    setErr('');
    setMsg('');
    try {
      const tags = f.tags
        .split(',')
        .map(t => t.trim())
        .filter(Boolean);

      const body: Record<string, unknown> = {
        title: f.title.trim(),
        description: f.description.trim(),
        tags,
        profession_key: selected()?.key,
      };
      if (f.budget_min) body.budget_min = Number(f.budget_min);
      if (f.budget_max) body.budget_max = Number(f.budget_max);
      if (f.location) body.location = f.location.trim();
      if (f.area) body.area = f.area.trim();

      const res = await apiFetch('/api/customers/requirements', {
        method: 'POST',
        body: JSON.stringify(body),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || 'Failed to post requirement.');
        return;
      }
      setMsg(`Your requirement has been posted! Professionals will respond shortly.`);
      setShowForm(false);
      setSelected(null);
    } catch {
      setErr('Network error. Please try again.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={{ 'max-width': '860px', display: 'grid', gap: '14px' }}>
      {/* Header */}
      <div style={{ background: NAVY, 'border-radius': '12px', padding: '16px 20px', display: 'flex', 'align-items': 'center', gap: '12px' }}>
        <span style={{ 'font-size': '26px' }}>🔍</span>
        <div>
          <p style={{ margin: 0, 'font-size': '18px', 'font-weight': '800', color: '#fff' }}>Browse Professionals</p>
          <p style={{ margin: '4px 0 0', 'font-size': '13px', color: 'rgba(255,255,255,0.65)' }}>
            Find the right professional for your need and post a requirement — they will reach out to you.
          </p>
        </div>
      </div>

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

      {/* How it works */}
      <div style={{ ...CARD, background: '#FFFBF8', border: `1px solid ${ORANGE}22` }}>
        <p style={{ margin: '0 0 8px', 'font-size': '13px', 'font-weight': '700', color: NAVY }}>How it works</p>
        <div style={{ display: 'grid', 'grid-template-columns': 'repeat(3, 1fr)', gap: '10px' }}>
          <For each={[
            ['1. Choose a category', 'Pick the type of professional you need'],
            ['2. Post your requirement', 'Describe what you need — budget, location, dates'],
            ['3. Get responses', 'Professionals respond; you shortlist and connect'],
          ]}>{([title, desc]) => (
            <div style={{ background: '#fff', 'border-radius': '10px', padding: '10px 12px', border: '1px solid #F3F4F6' }}>
              <p style={{ margin: '0 0 3px', 'font-size': '12px', 'font-weight': '700', color: NAVY }}>{title}</p>
              <p style={{ margin: 0, 'font-size': '11px', color: '#6B7280' }}>{desc}</p>
            </div>
          )}</For>
        </div>
      </div>

      {/* Professional type grid */}
      <div style={{ display: 'grid', 'grid-template-columns': 'repeat(auto-fill, minmax(240px, 1fr))', gap: '12px' }}>
        <For each={PROFESSIONAL_TYPES}>
          {(type) => (
            <div style={{ ...CARD, display: 'flex', 'flex-direction': 'column', gap: '8px', transition: 'box-shadow 0.15s' }}>
              <div style={{ display: 'flex', 'align-items': 'center', gap: '10px' }}>
                <span style={{ 'font-size': '28px', 'line-height': 1 }}>{type.emoji}</span>
                <p style={{ margin: 0, 'font-size': '14px', 'font-weight': '800', color: NAVY }}>{type.label}</p>
              </div>
              <p style={{ margin: 0, 'font-size': '12px', color: '#6B7280', 'line-height': '1.5', flex: 1 }}>
                {type.description}
              </p>
              <div style={{ display: 'flex', 'flex-wrap': 'wrap', gap: '5px', 'margin-bottom': '4px' }}>
                <For each={type.tags.slice(0, 3)}>
                  {(tag) => (
                    <span style={{ 'font-size': '10px', 'font-weight': '600', padding: '2px 7px', 'border-radius': '10px', background: '#F3F4F6', color: '#6B7280' }}>
                      {tag}
                    </span>
                  )}
                </For>
              </div>
              <button
                type="button"
                onClick={() => openEnquiry(type)}
                style={{ ...BTN_ORANGE, width: '100%', height: '34px' }}
              >
                Post Requirement
              </button>
            </div>
          )}
        </For>
      </div>

      {/* Enquiry form modal overlay */}
      <Show when={showForm() && selected()}>
        <div
          style={{
            position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', 'z-index': 200,
            display: 'flex', 'align-items': 'center', 'justify-content': 'center', padding: '16px',
          }}
          onClick={(e) => { if (e.target === e.currentTarget) closeForm(); }}
        >
          <div style={{
            background: '#fff', 'border-radius': '16px', padding: '24px',
            width: '100%', 'max-width': '520px', 'max-height': '90vh', 'overflow-y': 'auto',
            'box-shadow': '0 20px 60px rgba(0,0,0,0.2)',
          }}>
            <div style={{ display: 'flex', 'align-items': 'center', gap: '10px', 'margin-bottom': '16px' }}>
              <span style={{ 'font-size': '24px' }}>{selected()!.emoji}</span>
              <div>
                <p style={{ margin: 0, 'font-size': '16px', 'font-weight': '800', color: NAVY }}>
                  Find a {selected()!.label}
                </p>
                <p style={{ margin: '2px 0 0', 'font-size': '12px', color: '#6B7280' }}>
                  Describe your requirement and professionals will respond.
                </p>
              </div>
            </div>

            <div style={{ display: 'grid', gap: '12px' }}>
              <div>
                <label style={LABEL}>Requirement Title *</label>
                <input
                  type="text"
                  value={form().title}
                  onInput={(e) => setForm(f => ({ ...f, title: e.currentTarget.value }))}
                  placeholder={`e.g. Wedding photographer for Dec 2025`}
                  style={INPUT}
                />
              </div>

              <div>
                <label style={LABEL}>Description *</label>
                <textarea
                  rows={4}
                  value={form().description}
                  onInput={(e) => setForm(f => ({ ...f, description: e.currentTarget.value }))}
                  placeholder="Describe what you need — occasion, dates, style, any special requirements..."
                  style={{ ...INPUT, height: 'auto', padding: '10px 12px', resize: 'vertical' }}
                />
              </div>

              <div style={{ display: 'grid', 'grid-template-columns': '1fr 1fr', gap: '10px' }}>
                <div>
                  <label style={LABEL}>Budget Min (₹)</label>
                  <input
                    type="number"
                    value={form().budget_min}
                    onInput={(e) => setForm(f => ({ ...f, budget_min: e.currentTarget.value }))}
                    placeholder="e.g. 5000"
                    style={INPUT}
                  />
                </div>
                <div>
                  <label style={LABEL}>Budget Max (₹)</label>
                  <input
                    type="number"
                    value={form().budget_max}
                    onInput={(e) => setForm(f => ({ ...f, budget_max: e.currentTarget.value }))}
                    placeholder="e.g. 20000"
                    style={INPUT}
                  />
                </div>
              </div>

              <div style={{ display: 'grid', 'grid-template-columns': '1fr 1fr', gap: '10px' }}>
                <div>
                  <label style={LABEL}>City / Location</label>
                  <input
                    type="text"
                    value={form().location}
                    onInput={(e) => setForm(f => ({ ...f, location: e.currentTarget.value }))}
                    placeholder="e.g. Mumbai"
                    style={INPUT}
                  />
                </div>
                <div>
                  <label style={LABEL}>Area</label>
                  <input
                    type="text"
                    value={form().area}
                    onInput={(e) => setForm(f => ({ ...f, area: e.currentTarget.value }))}
                    placeholder="e.g. Andheri West"
                    style={INPUT}
                  />
                </div>
              </div>

              <div>
                <label style={LABEL}>Tags (comma separated)</label>
                <input
                  type="text"
                  value={form().tags}
                  onInput={(e) => setForm(f => ({ ...f, tags: e.currentTarget.value }))}
                  placeholder="e.g. Wedding, Outdoor, Candid"
                  style={INPUT}
                />
              </div>

              <Show when={err()}>
                <p style={{ margin: 0, 'font-size': '12px', color: '#B91C1C', 'font-weight': '600' }}>{err()}</p>
              </Show>

              <div style={{ display: 'flex', gap: '10px', 'justify-content': 'flex-end', 'margin-top': '4px' }}>
                <button type="button" onClick={closeForm} style={BTN_GHOST}>Cancel</button>
                <button
                  type="button"
                  onClick={submitEnquiry}
                  disabled={saving()}
                  style={{ ...BTN_PRIMARY, opacity: saving() ? '0.7' : '1', padding: '0 20px' }}
                >
                  {saving() ? 'Posting...' : 'Post Requirement'}
                </button>
              </div>
            </div>
          </div>
        </div>
      </Show>
    </div>
  );
}
