import * as React from 'react';
import { router } from '@inertiajs/react';
import AdminLayout from '../layout'; 
import { CornerDownLeft } from 'lucide-react';
import { offersApi, type Offer } from '@/features/admin/offers/services/api';
import { ApiError } from '@/lib/ApiError';
import { useNumericRouteParam } from '@/lib/useRouteParam';
import { Card, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input, Textarea } from '@/components/ui/input';
import { isoToDateString } from '@/lib/utils';
import { FormField } from '@/components/ui/form-field';
import { Spinner } from '@/components/ui/spinner';
import { toast } from '@/components/ui/sonner';

/** Edit an offer's marketing copy, coupon and validity window. score_slot is fixed and read-only. */
export default function OffersEdit() {
    const offerId = useNumericRouteParam();
    const [offer, setOffer] = React.useState<Offer | null>(null);
    const [form, setForm] = React.useState<Omit<
        Offer,
        'id' | 'score_slot' | 'created_at' | 'updated_at'
    > | null>(null);
    const [errors, setErrors] = React.useState<Record<string, string>>({});
    const [submitting, setSubmitting] = React.useState(false);

    React.useEffect(() => {
        if (!offerId) return;
        offersApi
            .show(offerId)
            .then((offer) => {
                setOffer(offer);
                const {
                    id: _id,
                    score_slot: _scoreSlot,
                    created_at: _createdAt,
                    updated_at: _updatedAt,
                    ...rest
                } = offer;
                setForm(rest);
            })
            .catch(() => toast.error('Failed to load offer.'));
    }, [offerId]);

    async function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        if (!form || !offerId) return;
        setSubmitting(true);
        setErrors({});
        try {
            await offersApi.update({ id: offerId, ...form });
            toast.success('Offer updated.');
            router.visit('/admin/offers');
        } catch (err) {
            if (err instanceof ApiError && err.isValidationError) {
                const flat: Record<string, string> = {};
                for (const [k, v] of Object.entries(err.errors ?? {}))
                    flat[k] = v[0];
                setErrors(flat);
            } else {
                toast.error('Failed to update offer.');
            }
        } finally {
            setSubmitting(false);
        }
    }

    if (!offer || !form) {
        return (
            <AdminLayout title="Edit offer">
                <div className="flex justify-center py-24">
                    <Spinner className="h-6 w-6 text-(--color-accent)" />
                </div>
            </AdminLayout>
        );
    } 

    function addTermsLineBreak() {
        const el = document.getElementById('terms') as HTMLTextAreaElement | null;
        const value = form?.terms ?? '';
        if (!value.trim()) return;

        // Find the end of the line the cursor is on and insert the break there.
        const caret = el?.selectionStart ?? value.length;
        const lineEnd = value.indexOf('\n', caret);
        const pos = lineEnd === -1 ? value.length : lineEnd;

        setForm((prev) =>
            prev
                ? { ...prev, terms: value.slice(0, pos) + '\n' + value.slice(pos) }
                : prev,
        );

        // Wait for React to update the value, then put the cursor on the new line.
        requestAnimationFrame(() => {
            el?.focus();
            el?.setSelectionRange(pos + 1, pos + 1);
        });
    }

    return (
        <AdminLayout title={`Edit offer — score slot ${offer.score_slot}`}>
            <form onSubmit={handleSubmit}>
                <Card className="max-w-xl">
                    <CardContent className="space-y-4">
                        <FormField
                            label="Title"
                            htmlFor="title"
                            required
                            error={errors.title}
                        >
                            <Input
                                id="title"
                                required
                                value={form.title}
                                onChange={(e) =>
                                    setForm({ ...form, title: e.target.value })
                                }
                            />
                        </FormField>
                        <FormField
                            label="Tagline"
                            htmlFor="tagline"
                            error={errors.tagline}
                        >
                            <Input
                                id="tagline"
                                value={form.tagline ?? ''}
                                onChange={(e) =>
                                    setForm({
                                        ...form,
                                        tagline: e.target.value,
                                    })
                                }
                            />
                        </FormField>
                        <div className="relative">
                            <Button
                                type="button"
                                variant="primary"
                                onMouseDown={(e) => e.preventDefault()}
                                onClick={addTermsLineBreak}
                                disabled={!form.terms?.trim()}
                                aria-label="Add line break to terms"
                                className="absolute top-0 right-0 h-6 gap-1 px-2 text-xs"
                            >
                                <CornerDownLeft className="h-3.5 w-3.5" />
                                Line break
                            </Button>
                            <FormField label="Terms" htmlFor="terms" error={errors.terms}>
                                <Textarea
                                    id="terms"
                                    rows={4}
                                    value={form.terms ?? ''} 
                                    className='mt-2'
                                    onChange={(e) =>
                                        setForm({ ...form, terms: e.target.value })
                                    }
                                />
                            </FormField>
                        </div>
                        <FormField
                            label="Discount"
                            htmlFor="discount"
                            required
                            error={errors.discount}
                        >
                            <Input
                                id="discount"
                                type="number"
                                required
                                min="0"
                                value={form.discount ?? ''}
                                onChange={(e) =>
                                    setForm({
                                        ...form,
                                        discount: e.target.value
                                            ? parseInt(e.target.value)
                                            : 0,
                                    })
                                }
                            />
                        </FormField>
                        <FormField
                            label="Coupon code"
                            htmlFor="coupon_code"
                            required
                            error={errors.coupon_code}
                        >
                            <Input
                                id="coupon_code"
                                required
                                className="font-mono"
                                value={form.coupon_code}
                                onChange={(e) =>
                                    setForm({
                                        ...form,
                                        coupon_code: e.target.value,
                                    })
                                }
                            />
                        </FormField>
                        <FormField
                            label="DLT template ID"
                            htmlFor="dlt_template_id"
                            required
                            error={errors.dlt_template_id}
                        >
                            <Input
                                id="dlt_template_id"
                                required
                                value={form.dlt_template_id}
                                onChange={(e) =>
                                    setForm({
                                        ...form,
                                        dlt_template_id: e.target.value,
                                    })
                                }
                            />
                        </FormField>
                        <FormField
                            label="SMS template body"
                            htmlFor="sms_template_body"
                            required
                            error={errors.sms_template_body}
                        >
                            <Textarea
                                id="sms_template_body"
                                rows={3}
                                value={form.sms_template_body}
                                onChange={(e) =>
                                    setForm({
                                        ...form,
                                        sms_template_body: e.target.value,
                                    })
                                }
                            />
                        </FormField>
                        <div className="grid gap-4 sm:grid-cols-2">
                            <FormField
                                label="Valid from"
                                htmlFor="valid_from"
                                error={errors.valid_from}
                            >
                                <Input
                                    id="valid_from"
                                    type="date"
                                    value={isoToDateString(form.valid_from)}
                                    onChange={(e) =>
                                        setForm({
                                            ...form,
                                            valid_from: e.target.value || null,
                                        })
                                    }
                                />
                            </FormField>
                            <FormField
                                label="Valid to"
                                htmlFor="valid_to"
                                error={errors.valid_to}
                            >
                                <Input
                                    id="valid_to"
                                    type="date"
                                    value={isoToDateString(form.valid_to)}
                                    onChange={(e) =>
                                        setForm({
                                            ...form,
                                            valid_to: e.target.value || null,
                                        })
                                    }
                                />
                            </FormField>
                        </div>
                        <label className="flex items-center gap-2 text-sm text-(--color-ink)">
                            <input
                                type="checkbox"
                                checked={form.active}
                                onChange={(e) =>
                                    setForm({
                                        ...form,
                                        active: e.target.checked,
                                    })
                                }
                            />
                            Active
                        </label>
                    </CardContent>
                    <CardFooter>
                        <Button
                            type="button"
                            variant="outline"
                            onClick={() => router.visit('/admin/offers')}
                        >
                            Cancel
                        </Button>
                        <Button type="submit" loading={submitting}>
                            Save changes
                        </Button>
                    </CardFooter>
                </Card>
            </form>
        </AdminLayout>
    );
}
