'use client';

import { Suspense, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { ClipboardList, MapPin } from 'lucide-react';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { LocationPicker, buildJobLocation, type JobLocationValue } from '@/components/map/LocationPicker';
import {
  PortalLoading,
  PortalSection,
  PortalShell,
} from '@/components/portal/Portal';
import type { ServiceAreaKey } from '@/lib/geocode';
import { api } from '@/lib/api';

function CreateJobContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const initialCategoryId = searchParams.get('categoryId') ?? '';

  const [categories, setCategories] = useState<{ id: string; name: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [form, setForm] = useState({
    title: '',
    description: '',
    categoryId: initialCategoryId,
    budget: '',
  });
  const [location, setLocation] = useState<JobLocationValue>(
    buildJobLocation('DAVAO_CITY' as ServiceAreaKey, '')
  );

  useEffect(() => {
    api<{ data: { id: string; name: string }[] }>('/categories')
      .then((res) => setCategories(res.data))
      .catch(console.error);
  }, []);

  useEffect(() => {
    if (initialCategoryId) {
      setForm((prev) => ({ ...prev, categoryId: initialCategoryId }));
    }
  }, [initialCategoryId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      const res = await api<{ data: { id: string } }>('/jobs', {
        method: 'POST',
        body: JSON.stringify({
          title: form.title,
          description: form.description,
          categoryId: form.categoryId,
          budget: form.budget ? parseFloat(form.budget) : undefined,
          location: location.location,
          latitude: location.latitude,
          longitude: location.longitude,
        }),
      });
      router.push(`/customer/jobs/${res.data.id}`);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to create job');
    } finally {
      setLoading(false);
    }
  };

  return (
    <DashboardLayout role="customer" title="Create Job">
      <PortalShell>
        <form onSubmit={handleSubmit} className="space-y-6">
          <PortalSection
            icon={ClipboardList}
            title="Job details"
            description="Tell workers what you need done"
          >
            <div className="space-y-4">
              <Input
                label="Job title"
                value={form.title}
                onChange={(e) => setForm({ ...form, title: e.target.value })}
                required
              />
              <div>
                <label className="text-sm font-medium text-slate-700">Category</label>
                <select
                  value={form.categoryId}
                  onChange={(e) => setForm({ ...form, categoryId: e.target.value })}
                  className="form-select mt-1.5 w-full"
                  required
                >
                  <option value="">Select category</option>
                  {categories.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="text-sm font-medium text-slate-700">Description</label>
                <textarea
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  rows={5}
                  className="form-textarea mt-1.5 w-full resize-y"
                  placeholder="Describe the work..."
                  required
                />
              </div>
              <Input
                label="Budget (PHP)"
                type="number"
                value={form.budget}
                onChange={(e) => setForm({ ...form, budget: e.target.value })}
                placeholder="Optional — leave blank if negotiable"
              />
            </div>
          </PortalSection>

          <PortalSection icon={MapPin} title="Location" description="Where the work will take place">
            <LocationPicker value={location} onChange={setLocation} />
          </PortalSection>

          {error ? <p className="text-sm text-red-500">{error}</p> : null}

          <Button type="submit" className="w-full sm:w-auto sm:min-w-[200px]" disabled={loading || !form.categoryId}>
            {loading ? 'Posting…' : 'Post job'}
          </Button>
        </form>
      </PortalShell>
    </DashboardLayout>
  );
}

export default function CreateJobPage() {
  return (
    <Suspense
      fallback={
        <DashboardLayout role="customer" title="Create Job">
          <PortalShell>
            <PortalLoading label="Loading…" />
          </PortalShell>
        </DashboardLayout>
      }
    >
      <CreateJobContent />
    </Suspense>
  );
}
