import PageHeader from '@/components/admin/PageHeader';
import { ImageUploader } from '@/components/ImageUploader';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
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, Radio, Save } from 'lucide-react';

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

interface TestimonialData {
    id: string;
    quote: string;
    name: string;
    role: string | null;
    company: string | null;
    location: string | null;
    metric: string | null;
    published_at: string | null;
    status: string;
    avatar_url: string | null;
    created_at: string;
}

interface Props {
    testimonial?: TestimonialData;
}

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

export default function TestimonialForm({ testimonial }: Props) {
    const isEdit = !!testimonial;

    const { data, setData, post, put, processing, errors } = useForm({
        quote: testimonial?.quote ?? '',
        name: testimonial?.name ?? '',
        role: testimonial?.role ?? '',
        company: testimonial?.company ?? '',
        location: testimonial?.location ?? '',
        metric: testimonial?.metric ?? '',
        published_at: testimonial?.published_at
            ? testimonial.published_at.substring(0, 16)
            : '',
        avatar: null as File | null,
        remove_avatar: false,
    });

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

    return (
        <AdminLayout
            title={isEdit ? 'Edit Testimonial' : 'New Testimonial'}
            breadcrumbs={[
                { label: 'Testimonials', href: '/admin/testimonials' },
                { label: isEdit ? 'Edit' : 'New' },
            ]}
        >
            <Head title={isEdit ? 'Edit Testimonial' : 'New Testimonial'} />

            <div className="p-6 lg:p-8">
                <div className="mb-6 flex items-center gap-3">
                    <Link
                        href="/admin/testimonials"
                        className="text-muted-foreground hover:text-foreground transition-colors"
                    >
                        <ArrowLeft className="h-4 w-4" />
                    </Link>
                    <PageHeader
                        title={isEdit ? 'Edit Testimonial' : 'New Testimonial'}
                    />
                </div>

                <form
                    onSubmit={handleSubmit}
                    className="mx-auto max-w-2xl space-y-5"
                >
                    {/* Avatar */}
                    <div className="space-y-1.5">
                        <label className="text-foreground text-sm font-medium">
                            Photo
                        </label>
                        <ImageUploader
                            url={
                                data.avatar
                                    ? null
                                    : (testimonial?.avatar_url ?? null)
                            }
                            name={data.name || 'Testimonial'}
                            size="md"
                            cropShape="round"
                            onSelect={(file) => {
                                setData('avatar', file);
                                setData('remove_avatar', !file);
                            }}
                        />
                    </div>

                    {/* Quote */}
                    <div className="space-y-1.5">
                        <label className="text-foreground text-sm font-medium">
                            Quote <span className="text-destructive">*</span>
                        </label>
                        <Textarea
                            value={data.quote}
                            onChange={(e) => setData('quote', e.target.value)}
                            rows={4}
                            placeholder="What did the customer say?"
                            className={cn(
                                'resize-y',
                                errors.quote && 'border-destructive',
                            )}
                        />
                        {errors.quote && (
                            <p className="text-destructive text-xs">
                                {errors.quote}
                            </p>
                        )}
                    </div>

                    {/* Name */}
                    <div className="space-y-1.5">
                        <label className="text-foreground text-sm font-medium">
                            Name <span className="text-destructive">*</span>
                        </label>
                        <Input
                            value={data.name}
                            onChange={(e) => setData('name', e.target.value)}
                            placeholder="Jane Doe"
                            className={cn(errors.name && 'border-destructive')}
                        />
                        {errors.name && (
                            <p className="text-destructive text-xs">
                                {errors.name}
                            </p>
                        )}
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-1.5">
                            <label className="text-foreground text-sm font-medium">
                                Role
                            </label>
                            <Input
                                value={data.role}
                                onChange={(e) =>
                                    setData('role', e.target.value)
                                }
                                placeholder="e.g. Operations Manager"
                            />
                        </div>
                        <div className="space-y-1.5">
                            <label className="text-foreground text-sm font-medium">
                                Company
                            </label>
                            <Input
                                value={data.company}
                                onChange={(e) =>
                                    setData('company', e.target.value)
                                }
                            />
                        </div>
                        <div className="space-y-1.5">
                            <label className="text-foreground text-sm font-medium">
                                Location
                            </label>
                            <Input
                                value={data.location}
                                onChange={(e) =>
                                    setData('location', e.target.value)
                                }
                                placeholder="e.g. Nairobi, Kenya"
                            />
                        </div>
                        <div className="space-y-1.5">
                            <label className="text-foreground text-sm font-medium">
                                Metric
                            </label>
                            <Input
                                value={data.metric}
                                onChange={(e) =>
                                    setData('metric', e.target.value)
                                }
                                placeholder="e.g. 40% faster loan processing"
                            />
                        </div>
                    </div>

                    {/* Publish date */}
                    <div className="space-y-1.5">
                        <label className="text-foreground text-sm font-medium">
                            Publish date
                        </label>
                        <Input
                            type="datetime-local"
                            value={data.published_at}
                            onChange={(e) =>
                                setData('published_at', e.target.value)
                            }
                            className={cn(
                                errors.published_at && 'border-destructive',
                            )}
                        />
                        <p className="text-muted-foreground text-xs">
                            Leave blank to save as draft. Set a future time to
                            schedule.
                        </p>
                        {errors.published_at && (
                            <p className="text-destructive text-xs">
                                {errors.published_at}
                            </p>
                        )}
                    </div>

                    {/* Actions */}
                    <div className="border-border flex items-center justify-between border-t pt-5">
                        <Link
                            href="/admin/testimonials"
                            className="text-muted-foreground hover:text-foreground text-sm transition-colors"
                        >
                            Cancel
                        </Link>
                        <div className="flex items-center gap-2">
                            {data.published_at && (
                                <Button
                                    type="button"
                                    variant="outline"
                                    size="sm"
                                    disabled={processing}
                                    onClick={() => {
                                        setData('published_at', '');
                                        setTimeout(() => {
                                            (
                                                document.querySelector(
                                                    'form',
                                                ) as HTMLFormElement
                                            )?.requestSubmit();
                                        }, 0);
                                    }}
                                >
                                    Save as draft
                                </Button>
                            )}
                            <Button
                                type="submit"
                                disabled={processing}
                                size="sm"
                                className="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>
                        </div>
                    </div>
                </form>
            </div>
        </AdminLayout>
    );
}
