'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

interface JobInfo {
  id: number;
  title: string;
  location: string;
  experience_band?: string;
  ctc_band?: string;
  shift?: string;
  must_have_skills?: string;
  client_name?: string | null;
}

const W = 1080;
const H = 1080;

/** Draws a shareable 1080×1080 job-post creative on a canvas and offers PNG download. */
export default function JobPostCard({ job }: { job: JobInfo }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [dataUrl, setDataUrl] = useState<string>('');

  const draw = useCallback(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // Background — brand gradient
    const bg = ctx.createLinearGradient(0, 0, W, H);
    bg.addColorStop(0, '#405189');
    bg.addColorStop(0.55, '#3b4a7e');
    bg.addColorStop(1, '#28345c');
    ctx.fillStyle = bg;
    ctx.fillRect(0, 0, W, H);

    // Decorative circles
    ctx.fillStyle = 'rgba(255,255,255,0.06)';
    ctx.beginPath(); ctx.arc(W - 80, 100, 220, 0, Math.PI * 2); ctx.fill();
    ctx.beginPath(); ctx.arc(60, H - 60, 160, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = 'rgba(10,179,156,0.15)';
    ctx.beginPath(); ctx.arc(W - 140, H - 180, 120, 0, Math.PI * 2); ctx.fill();

    // Company / brand
    ctx.fillStyle = '#0ab39c';
    ctx.font = 'bold 34px Poppins, Arial, sans-serif';
    ctx.fillText((job.client_name || 'TA-ATS').toUpperCase(), 80, 120);

    // WE'RE HIRING
    ctx.fillStyle = '#ffffff';
    ctx.font = '800 92px Poppins, Arial, sans-serif';
    ctx.fillText("WE'RE HIRING", 80, 250);

    // Accent underline
    ctx.fillStyle = '#0ab39c';
    ctx.fillRect(80, 285, 240, 10);

    // Job title (wraps to two lines if long)
    ctx.fillStyle = '#ffffff';
    ctx.font = '700 64px Poppins, Arial, sans-serif';
    const words = job.title.split(' ');
    let line = '';
    let y = 420;
    for (const word of words) {
      const test = line ? `${line} ${word}` : word;
      if (ctx.measureText(test).width > W - 160 && line) {
        ctx.fillText(line, 80, y);
        line = word;
        y += 80;
      } else {
        line = test;
      }
    }
    ctx.fillText(line, 80, y);

    // Detail rows
    const details: Array<[string, string]> = [
      ['📍  Location', job.location || '—'],
      ['💼  Experience', job.experience_band || '—'],
      ['💰  CTC', job.ctc_band || '—'],
      ['🕘  Shift', job.shift || '—'],
    ];
    let dy = y + 110;
    for (const [label, value] of details) {
      ctx.fillStyle = 'rgba(255,255,255,0.55)';
      ctx.font = '600 30px Poppins, Arial, sans-serif';
      ctx.fillText(label, 80, dy);
      ctx.fillStyle = '#ffffff';
      ctx.font = '700 36px Poppins, Arial, sans-serif';
      ctx.fillText(value, 420, dy);
      dy += 72;
    }

    // Skills chips
    const skills = (job.must_have_skills || '')
      .split(/[,\n]/).map((s) => s.trim()).filter(Boolean).slice(0, 5);
    if (skills.length) {
      let cx = 80;
      const cy = dy + 20;
      ctx.font = '600 28px Poppins, Arial, sans-serif';
      for (const skill of skills) {
        const w = ctx.measureText(skill).width + 48;
        if (cx + w > W - 80) break;
        ctx.fillStyle = 'rgba(255,255,255,0.12)';
        ctx.beginPath();
        ctx.roundRect(cx, cy, w, 56, 28);
        ctx.fill();
        ctx.fillStyle = '#ffffff';
        ctx.fillText(skill, cx + 24, cy + 38);
        cx += w + 16;
      }
      dy = cy + 90;
    }

    // Footer — apply bar
    ctx.fillStyle = '#0ab39c';
    ctx.beginPath();
    ctx.roundRect(80, H - 150, W - 160, 84, 42);
    ctx.fill();
    ctx.fillStyle = '#ffffff';
    ctx.font = '700 34px Poppins, Arial, sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText(`Apply now  •  careers portal  •  Job #${job.id}`, W / 2, H - 96);
    ctx.textAlign = 'left';

    setDataUrl(canvas.toDataURL('image/png'));
  }, [job]);

  // Draw after fonts are ready so Poppins renders into the PNG.
  useEffect(() => {
    draw();
    if (typeof document !== 'undefined' && 'fonts' in document) {
      (document as any).fonts.ready.then(() => draw());
    }
  }, [draw]);

  return (
    <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-6 shadow-sm">
      <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
        <div>
          <h3 className="text-sm font-bold text-slate-800 dark:text-white">Job Post Creative</h3>
          <p className="text-xs text-slate-400 mt-0.5">Auto-generated PNG from this JD — attach it when posting on LinkedIn, Naukri, etc.</p>
        </div>
        <a
          href={dataUrl || undefined}
          download={`job-post-${job.id}.png`}
          className={`inline-flex items-center gap-2 text-xs font-bold px-4 py-2.5 rounded-none transition ${
            dataUrl
              ? 'bg-indigo-600 hover:bg-indigo-500 text-white shadow-lg cursor-pointer'
              : 'bg-slate-200 text-slate-400 cursor-not-allowed'
          }`}
        >
          <i className="fa-solid fa-download" /> Download PNG
        </a>
      </div>
      <div className="flex justify-center bg-slate-50 dark:bg-slate-950 border border-slate-100 dark:border-slate-800 rounded-none p-4">
        <canvas
          ref={canvasRef}
          width={W}
          height={H}
          className="w-full max-w-[420px] h-auto rounded-none shadow-md"
        />
      </div>
    </div>
  );
}
