import { RichTextEditor } from '@/components/admin/RichTextEditor';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import AdminLayout from '@/Layouts/AdminLayout';
import { cn } from '@/lib/utils';
import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Briefcase, Radio, Save } from 'lucide-react';

// ── Types ─────────────────────────────────────────────────────────────────────

interface JobOpeningData {
    id: string;
    title: string;
    slug: string;
    team: string | null;
    location: string | null;
    employment_type: string | null;
    summary: string | null;
    description: string | null;
    requirements: string;
    tags: string;
    apply_url: string | null;
    published_at: string | null;
    status: string;
    created_at: string;
}

interface Props {
    jobOpening?: JobOpeningData;
}

const TEAM_OPTIONS = [
    'Engineering',
    'Product',
    'Design',
    'Sales',
    'Customer Success',
    'Marketing',
    'Operations',
];

const EMPLOYMENT_TYPE_OPTIONS = [
    'Full-time',
    'Part-time',
    'Contract',
    'Internship',
];

// ── Helpers ───────────────────────────────────────────────────────────────────

function Field({
    label,
    error,
    hint,
    children,
}: {
    label: string;
    error?: string;
    hint?: string;
    children: React.ReactNode;
}) {
    return (
        <div className="space-y-1.5">
            <label className="text-muted-foreground block text-xs font-semibold tracking-wide uppercase">
                {label}
            </label>
            {children}
            {hint && !error && (
                <p className="text-muted-foreground text-xs">{hint}</p>
            )}
            {error && <p className="text-destructive text-xs">{error}</p>}
        </div>
    );
}

function Card({
    title,
    children,
}: {
    title: string;
    children: React.ReactNode;
}) {
    return (
        <div className="pf-glass space-y-5 rounded-xl p-6">
            <p className="text-muted-foreground dark:text-muted-foreground/50 text-[10px] font-bold tracking-widest uppercase">
                {title}
            </p>
            {children}
        </div>
    );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default function JobOpeningForm({ jobOpening }: Props) {
    const isEdit = !!jobOpening;

    const { data, setData, post, put, processing, errors } = useForm({
        title: jobOpening?.title ?? '',
        slug: jobOpening?.slug ?? '',
        team: jobOpening?.team ?? '',
        location: jobOpening?.location ?? '',
        employment_type: jobOpening?.employment_type ?? 'Full-time',
        summary: jobOpening?.summary ?? '',
        description: jobOpening?.description ?? '',
        requirements: jobOpening?.requirements ?? '',
        tags: jobOpening?.tags ?? '',
        apply_url: jobOpening?.apply_url ?? '',
        published_at: jobOpening?.published_at
            ? jobOpening.published_at.substring(0, 16)
            : '',
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (isEdit) {
            put(`/admin/careers/${jobOpening.id}`);
        } else {
            post('/admin/careers');
        }
    };

    return (
        <AdminLayout
            title={isEdit ? 'Edit Job Opening' : 'New Job Opening'}
            breadcrumbs={[
                { label: 'Careers', href: '/admin/careers' },
                { label: isEdit ? 'Edit' : 'New' },
            ]}
        >
            <Head title={isEdit ? 'Edit Job Opening' : 'New Job Opening'} />

            <form onSubmit={handleSubmit} className="p-6 lg:p-8">
                <div className="mb-6 flex items-center gap-3">
                    <Link
                        href="/admin/careers"
                        className="border-border text-muted-foreground hover:bg-muted/40 hover:text-foreground flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border transition-colors"
                    >
                        <ArrowLeft className="h-4 w-4" />
                    </Link>
                    <Briefcase className="text-primary h-5 w-5" />
                    <h1 className="text-foreground text-lg font-bold">
                        {isEdit ? 'Edit Job Opening' : 'New Job Opening'}
                    </h1>
                </div>

                <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr_360px]">
                    {/* ── Main column ──────────────────────────────────────── */}
                    <div className="flex flex-col gap-6">
                        <Card title="Role">
                            <Field label="Title" error={errors.title}>
                                <Input
                                    value={data.title}
                                    onChange={(e) => {
                                        setData('title', e.target.value);
                                        if (!isEdit) {
                                            setData(
                                                'slug',
                                                e.target.value
                                                    .toLowerCase()
                                                    .trim()
                                                    .replace(/[^a-z0-9]+/g, '-')
                                                    .replace(/(^-|-$)/g, ''),
                                            );
                                        }
                                    }}
                                    placeholder="e.g. Senior Backend Engineer"
                                    className={cn(
                                        'text-base font-semibold',
                                        errors.title && 'border-destructive',
                                    )}
                                />
                            </Field>

                            <Field label="Slug" error={errors.slug}>
                                <Input
                                    value={data.slug}
                                    onChange={(e) =>
                                        setData('slug', e.target.value)
                                    }
                                    placeholder="senior-backend-engineer"
                                    className={cn(
                                        errors.slug && 'border-destructive',
                                    )}
                                />
                            </Field>

                            <Field
                                label="Summary"
                                error={errors.summary}
                                hint="Short one-liner shown on the role card."
                            >
                                <Textarea
                                    value={data.summary ?? ''}
                                    onChange={(e) =>
                                        setData('summary', e.target.value)
                                    }
                                    rows={2}
                                    placeholder="What's this role about, in a sentence?"
                                    className={cn(
                                        'resize-y',
                                        errors.summary && 'border-destructive',
                                    )}
                                />
                            </Field>
                        </Card>

                        <Card title="Description">
                            <RichTextEditor
                                value={data.description ?? ''}
                                onChange={(html) =>
                                    setData('description', html)
                                }
                                placeholder="Describe the role, responsibilities, and team…"
                            />
                        </Card>

                        <Card title="Requirements">
                            <Field
                                label="Requirements"
                                hint="One requirement per line."
                                error={errors.requirements}
                            >
                                <Textarea
                                    value={data.requirements}
                                    onChange={(e) =>
                                        setData('requirements', e.target.value)
                                    }
                                    rows={6}
                                    placeholder={
                                        '5+ years of backend engineering experience\nStrong knowledge of PHP and Laravel\nExperience with PostgreSQL at scale'
                                    }
                                    className="resize-y"
                                />
                            </Field>
                        </Card>
                    </div>

                    {/* ── Sidebar ──────────────────────────────────────────── */}
                    <div className="flex flex-col gap-6">
                        <Card title="Publish">
                            <Field
                                label="Publish date"
                                error={errors.published_at}
                                hint="Leave blank to save as draft. Set a future time to schedule."
                            >
                                <Input
                                    type="datetime-local"
                                    value={data.published_at}
                                    onChange={(e) =>
                                        setData('published_at', e.target.value)
                                    }
                                    className={cn(
                                        errors.published_at &&
                                            'border-destructive',
                                    )}
                                />
                            </Field>

                            <div className="flex flex-col gap-2 pt-1">
                                <Button
                                    type="submit"
                                    disabled={processing}
                                    className="w-full gap-2"
                                >
                                    {data.published_at ? (
                                        <>
                                            <Radio className="h-3.5 w-3.5" />
                                            {isEdit ? 'Update' : 'Publish'}
                                        </>
                                    ) : (
                                        <>
                                            <Save className="h-3.5 w-3.5" />
                                            Save draft
                                        </>
                                    )}
                                </Button>
                                {data.published_at && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        disabled={processing}
                                        className="w-full"
                                        onClick={() => {
                                            setData('published_at', '');
                                            setTimeout(() => {
                                                (
                                                    document.querySelector(
                                                        'form',
                                                    ) as HTMLFormElement
                                                )?.requestSubmit();
                                            }, 0);
                                        }}
                                    >
                                        Save as draft
                                    </Button>
                                )}
                                <Link
                                    href="/admin/careers"
                                    className="text-muted-foreground hover:text-foreground py-1 text-center text-sm transition-colors"
                                >
                                    Cancel
                                </Link>
                            </div>
                        </Card>

                        <Card title="Organization">
                            <Field label="Team">
                                <Select
                                    value={data.team ?? ''}
                                    onValueChange={(v) => setData('team', v)}
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select a team" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {TEAM_OPTIONS.map((t) => (
                                            <SelectItem key={t} value={t}>
                                                {t}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </Field>

                            <Field label="Employment type">
                                <Select
                                    value={data.employment_type ?? ''}
                                    onValueChange={(v) =>
                                        setData('employment_type', v)
                                    }
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select a type" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {EMPLOYMENT_TYPE_OPTIONS.map((t) => (
                                            <SelectItem key={t} value={t}>
                                                {t}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </Field>

                            <Field label="Location">
                                <Input
                                    value={data.location ?? ''}
                                    onChange={(e) =>
                                        setData('location', e.target.value)
                                    }
                                    placeholder="e.g. Nairobi / Remote"
                                />
                            </Field>

                            <Field
                                label="Tags"
                                hint="Separate multiple tags with commas."
                            >
                                <Input
                                    value={data.tags}
                                    onChange={(e) =>
                                        setData('tags', e.target.value)
                                    }
                                    placeholder="e.g. PHP, Laravel, PostgreSQL"
                                />
                            </Field>
                        </Card>

                        <Card title="Application">
                            <Field
                                label="Apply URL"
                                hint="Leave blank to use the default careers email."
                                error={errors.apply_url}
                            >
                                <Input
                                    value={data.apply_url ?? ''}
                                    onChange={(e) =>
                                        setData('apply_url', e.target.value)
                                    }
                                    placeholder="https://…"
                                />
                            </Field>
                        </Card>
                    </div>
                </div>
            </form>
        </AdminLayout>
    );
}
