import { useState } from 'react';
import { Link } from 'react-router-dom';
import { ArrowRight, Send, CheckCircle2, Heart, Zap, Users2, TrendingUp, Coffee, Plane, GraduationCap } from 'lucide-react';
import PageHero from '@/components/PageHero';
import CTASection from '@/components/CTASection';
import { Reveal, StaggerContainer, StaggerItem, SectionHeading } from '@/components/ui/Animation';
import { supabase } from '@/lib/supabase';

const openings = [
  { title: 'Senior Full-Stack Engineer', team: 'Engineering', location: 'Pune / Remote', type: 'Full-time' },
  { title: 'AI/ML Engineer', team: 'AI', location: 'Pune / Remote', type: 'Full-time' },
  { title: 'Product Designer', team: 'Design', location: 'Pune', type: 'Full-time' },
  { title: 'DevOps Engineer', team: 'Infrastructure', location: 'Remote', type: 'Full-time' },
  { title: 'Business Development Manager', team: 'Sales', location: 'Pune', type: 'Full-time' },
  { title: 'Technical Project Manager', team: 'Delivery', location: 'Pune / Remote', type: 'Full-time' },
];

const benefits = [
  { icon: TrendingUp, title: 'Real growth', text: 'Mentorship, conference budgets, and a clear path forward.' },
  { icon: Heart, title: 'Health first', text: 'Comprehensive health insurance for you and your family.' },
  { icon: Plane, title: 'Generous leave', text: '25 days PTO plus public holidays. Take real breaks.' },
  { icon: GraduationCap, title: 'Learning budget', text: 'Annual stipend for courses, books, and certifications.' },
  { icon: Coffee, title: 'Great workspace', text: 'A studio designed for focus, collaboration, and good coffee.' },
  { icon: Zap, title: 'Modern stack', text: 'Work with the best tools — no legacy maintenance hell.' },
];

const culture = [
  { icon: Users2, title: 'Small, senior teams', text: 'No layers of management. You work directly with people who build.' },
  { icon: Heart, title: 'Craft over churn', text: 'We’d rather do fewer things exceptionally than many things adequately.' },
  { icon: Zap, title: 'Ownership culture', text: 'You own outcomes, not tasks. Autonomy comes with trust.' },
];

export default function Careers() {
  const [form, setForm] = useState({ full_name: '', email: '', phone: '', position: '', cover_letter: '', experience: '' });
  const [status, setStatus] = useState<'idle' | 'submitting' | 'success' | 'error'>('idle');
  const [error, setError] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setForm((f) => ({ ...f, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setStatus('submitting');
    setError('');
    try {
      const { error: insertError } = await supabase.from('career_applications').insert({
        full_name: form.full_name,
        email: form.email,
        phone: form.phone || null,
        position: form.position,
        cover_letter: form.cover_letter || null,
        experience: form.experience || null,
      });
      if (insertError) throw insertError;
      setStatus('success');
      setForm({ full_name: '', email: '', phone: '', position: '', cover_letter: '', experience: '' });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Submission failed. Please try again.');
      setStatus('error');
    }
  };

  return (
    <div>
      <PageHero
        eyebrow="Careers"
        title={<>Build your career at <span className="gradient-text">Queneva</span></>}
        subtitle="We’re a senior team that values craft, autonomy, and impact. If you love building great software with great people, we’d love to meet you."
        crumbs={[{ label: 'Home', to: '/' }, { label: 'Careers' }]}
      />

      {/* Culture */}
      <section className="container-wide section-padding py-16">
        <SectionHeading eyebrow="Culture" title={<>How we <span className="gradient-text">work</span></>} />
        <StaggerContainer className="mt-14 grid gap-6 md:grid-cols-3">
          {culture.map((c) => (
            <StaggerItem key={c.title}>
              <div className="glass h-full rounded-3xl p-7 card-hover">
                <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-secondary-500/15 to-accent-500/15 text-secondary-500 dark:text-accent-400">
                  <c.icon size={22} />
                </div>
                <h3 className="mt-5 text-lg font-bold">{c.title}</h3>
                <p className="mt-2 text-sm text-primary-400 dark:text-gray-400">{c.text}</p>
              </div>
            </StaggerItem>
          ))}
        </StaggerContainer>
      </section>

      {/* Benefits */}
      <section className="container-wide section-padding py-16">
        <SectionHeading eyebrow="Benefits" title={<>We take care of <span className="gradient-text">our people</span></>} />
        <StaggerContainer className="mt-14 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {benefits.map((b) => (
            <StaggerItem key={b.title}>
              <div className="glass h-full rounded-3xl p-7 card-hover">
                <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-secondary-500 to-accent-500 text-white">
                  <b.icon size={22} />
                </div>
                <h3 className="mt-5 text-lg font-bold">{b.title}</h3>
                <p className="mt-2 text-sm text-primary-400 dark:text-gray-400">{b.text}</p>
              </div>
            </StaggerItem>
          ))}
        </StaggerContainer>
      </section>

      {/* Openings */}
      <section className="container-wide section-padding py-16">
        <SectionHeading eyebrow="Open roles" title={<>Current <span className="gradient-text">openings</span></>} subtitle="Don’t see your role? Send a general application below — we’re always looking for exceptional people." />
        <div className="mx-auto mt-12 max-w-4xl space-y-3">
          {openings.map((o, i) => (
            <Reveal key={o.title} delay={i * 0.04}>
              <div className="glass flex flex-col items-start justify-between gap-4 rounded-2xl p-6 card-hover sm:flex-row sm:items-center">
                <div>
                  <h3 className="font-bold">{o.title}</h3>
                  <div className="mt-1.5 flex flex-wrap gap-3 text-xs text-primary-400 dark:text-gray-500">
                    <span>{o.team}</span>
                    <span>·</span>
                    <span>{o.location}</span>
                    <span>·</span>
                    <span>{o.type}</span>
                  </div>
                </div>
                <button
                  onClick={() => {
                    setForm((f) => ({ ...f, position: o.title }));
                    document.getElementById('apply-form')?.scrollIntoView({ behavior: 'smooth' });
                  }}
                  className="btn-secondary !px-5 !py-2.5 text-xs"
                >
                  Apply <ArrowRight size={14} />
                </button>
              </div>
            </Reveal>
          ))}
        </div>
      </section>

      {/* Application form */}
      <section id="apply-form" className="container-wide section-padding py-16">
        <div className="mx-auto max-w-2xl">
          <SectionHeading eyebrow="Apply" title={<>Send us your <span className="gradient-text">application</span></>} />
          {status === 'success' ? (
            <Reveal className="mt-10">
              <div className="glass rounded-3xl p-10 text-center">
                <CheckCircle2 size={48} className="mx-auto text-accent-500" />
                <h3 className="mt-4 text-xl font-bold">Application received!</h3>
                <p className="mt-2 text-sm text-primary-400 dark:text-gray-400">
                  Thanks for applying. Our team will review your application and reach out if there’s a fit.
                </p>
                <Link to="/" className="btn-secondary mt-6">Back home</Link>
              </div>
            </Reveal>
          ) : (
            <Reveal className="mt-10">
              <form onSubmit={handleSubmit} className="glass space-y-5 rounded-3xl p-8">
                <div className="grid gap-5 sm:grid-cols-2">
                  <Field label="Full name" name="full_name" value={form.full_name} onChange={handleChange} required />
                  <Field label="Email" name="email" type="email" value={form.email} onChange={handleChange} required />
                </div>
                <div className="grid gap-5 sm:grid-cols-2">
                  <Field label="Phone" name="phone" value={form.phone} onChange={handleChange} />
                  <div>
                    <label className="mb-1.5 block text-sm font-medium text-primary-600 dark:text-gray-300">Position</label>
                    <select
                      name="position"
                      value={form.position}
                      onChange={handleChange}
                      required
                      className="w-full rounded-xl glass px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-secondary-500"
                    >
                      <option value="">Select a role</option>
                      {openings.map((o) => <option key={o.title} value={o.title}>{o.title}</option>)}
                      <option value="General">General application</option>
                    </select>
                  </div>
                </div>
                <Field label="Years of experience" name="experience" value={form.experience} onChange={handleChange} />
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-primary-600 dark:text-gray-300">Cover letter / message</label>
                  <textarea
                    name="cover_letter"
                    value={form.cover_letter}
                    onChange={handleChange}
                    rows={4}
                    className="w-full rounded-xl glass px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-secondary-500"
                  />
                </div>
                {status === 'error' && <p className="text-sm text-red-500">{error}</p>}
                <button type="submit" disabled={status === 'submitting'} className="btn-primary w-full disabled:opacity-60">
                  {status === 'submitting' ? 'Sending…' : <>Submit application <Send size={16} /></>}
                </button>
              </form>
            </Reveal>
          )}
        </div>
      </section>

      <CTASection title="Not ready to apply yet?" subtitle="Follow us or reach out — we’re always happy to chat." ctaLabel="Get in touch" />
    </div>
  );
}

function Field({ label, name, value, onChange, type = 'text', required }: {
  label: string; name: string; value: string; onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  type?: string; required?: boolean;
}) {
  return (
    <div>
      <label className="mb-1.5 block text-sm font-medium text-primary-600 dark:text-gray-300">{label}{required && ' *'}</label>
      <input
        type={type}
        name={name}
        value={value}
        onChange={onChange}
        required={required}
        className="w-full rounded-xl glass px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-secondary-500"
      />
    </div>
  );
}
