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,
    ArrowUpRight,
    Handshake,
    MapPin,
    Radio,
    Save,
} from 'lucide-react';
import { useEffect, useState } from 'react';

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

interface CustomerData {
    id: string;
    name: string;
    sector: string | null;
    country: string | null;
    location: string | null;
    website: string | null;
    description: string | null;
    since_year: number | null;
    published_at: string | null;
    status: string;
    logo_url: string | null;
    created_at: string;
}

interface Props {
    customer?: CustomerData;
}

const SECTOR_PRESETS = [
    'Microfinance Institution',
    'SACCO',
    'Community Lender',
    'Digital Lender',
];

const DESCRIPTION_MAX = 1000;

// ── 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>
    );
}

const STATUS_STYLES: Record<string, string> = {
    draft: 'bg-muted text-muted-foreground',
    scheduled:
        'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
    published:
        'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
};

function initials(name: string): string {
    return name
        .split(/\s+/)
        .filter(Boolean)
        .slice(0, 2)
        .map((word) => word[0])
        .join('')
        .toUpperCase();
}

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

export default function CustomerForm({ customer }: Props) {
    const isEdit = !!customer;

    const { data, setData, post, put, processing, errors } = useForm({
        name: customer?.name ?? '',
        sector: customer?.sector ?? '',
        country: customer?.country ?? '',
        location: customer?.location ?? '',
        website: customer?.website ?? '',
        description: customer?.description ?? '',
        since_year: customer?.since_year ? String(customer.since_year) : '',
        published_at: customer?.published_at
            ? customer.published_at.substring(0, 16)
            : '',
        logo: null as File | null,
        remove_logo: false,
    });

    // Live object URL for a freshly selected logo so the preview updates
    const [logoPreview, setLogoPreview] = useState<string | null>(null);
    useEffect(() => {
        if (!data.logo) {
            setLogoPreview(null);
            return;
        }
        const url = URL.createObjectURL(data.logo);
        setLogoPreview(url);
        return () => URL.revokeObjectURL(url);
    }, [data.logo]);

    const previewLogo =
        logoPreview ?? (data.remove_logo ? null : (customer?.logo_url ?? null));

    const status = !data.published_at
        ? 'draft'
        : new Date(data.published_at) > new Date()
          ? 'scheduled'
          : 'published';

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

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

            <form onSubmit={handleSubmit} className="p-6 lg:p-8">
                <div className="mb-6 flex items-center gap-3">
                    <Link
                        href="/admin/customers"
                        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>
                    <Handshake className="text-primary h-5 w-5" />
                    <h1 className="text-foreground text-lg font-bold">
                        {isEdit ? 'Edit Customer' : 'New Customer'}
                    </h1>
                    <span
                        className={cn(
                            'ml-auto inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-medium capitalize',
                            STATUS_STYLES[status],
                        )}
                    >
                        {status}
                    </span>
                </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="Institution">
                            <Field label="Name" error={errors.name}>
                                <Input
                                    value={data.name}
                                    onChange={(e) =>
                                        setData('name', e.target.value)
                                    }
                                    placeholder="e.g. Mwanga Microfinance"
                                    className={cn(
                                        'text-base font-semibold',
                                        errors.name && 'border-destructive',
                                    )}
                                />
                            </Field>

                            <Field label="Sector" error={errors.sector}>
                                <Input
                                    value={data.sector}
                                    onChange={(e) =>
                                        setData('sector', e.target.value)
                                    }
                                    placeholder="e.g. SACCO, Microfinance Institution"
                                />
                                <div className="flex flex-wrap gap-1.5 pt-1">
                                    {SECTOR_PRESETS.map((preset) => (
                                        <button
                                            key={preset}
                                            type="button"
                                            onClick={() =>
                                                setData('sector', preset)
                                            }
                                            className={cn(
                                                'rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors',
                                                data.sector === preset
                                                    ? 'border-primary/40 bg-primary/10 text-primary'
                                                    : 'border-border text-muted-foreground hover:bg-muted/40 hover:text-foreground',
                                            )}
                                        >
                                            {preset}
                                        </button>
                                    ))}
                                </div>
                            </Field>

                            <Field
                                label="Description"
                                error={errors.description}
                                hint={`${data.description.length}/${DESCRIPTION_MAX} — shown on the public card, first two lines visible.`}
                            >
                                <Textarea
                                    value={data.description}
                                    onChange={(e) =>
                                        setData(
                                            'description',
                                            e.target.value.slice(
                                                0,
                                                DESCRIPTION_MAX,
                                            ),
                                        )
                                    }
                                    rows={3}
                                    placeholder="Short blurb about the institution"
                                    className={cn(
                                        'resize-y',
                                        errors.description &&
                                            'border-destructive',
                                    )}
                                />
                            </Field>
                        </Card>

                        <Card title="Location & contact">
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                <Field label="Country" error={errors.country}>
                                    <Input
                                        value={data.country}
                                        onChange={(e) =>
                                            setData('country', e.target.value)
                                        }
                                        placeholder="e.g. Kenya"
                                    />
                                </Field>
                                <Field
                                    label="City / Location"
                                    error={errors.location}
                                >
                                    <Input
                                        value={data.location}
                                        onChange={(e) =>
                                            setData('location', e.target.value)
                                        }
                                        placeholder="e.g. Nairobi"
                                    />
                                </Field>
                            </div>

                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                <Field
                                    label="Website"
                                    error={errors.website}
                                    hint="Full URL, including https://"
                                >
                                    <Input
                                        type="url"
                                        value={data.website}
                                        onChange={(e) =>
                                            setData('website', e.target.value)
                                        }
                                        placeholder="https://example.org"
                                        className={cn(
                                            errors.website &&
                                                'border-destructive',
                                        )}
                                    />
                                </Field>
                                <Field
                                    label="Customer since"
                                    error={errors.since_year}
                                >
                                    <Input
                                        type="number"
                                        min={2000}
                                        max={new Date().getFullYear()}
                                        value={data.since_year}
                                        onChange={(e) =>
                                            setData(
                                                'since_year',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="e.g. 2023"
                                        className={cn(
                                            errors.since_year &&
                                                'border-destructive',
                                        )}
                                    />
                                </Field>
                            </div>
                        </Card>

                        <Card title="Logo">
                            <div className="flex items-start gap-5">
                                <ImageUploader
                                    url={
                                        data.logo
                                            ? null
                                            : (customer?.logo_url ?? null)
                                    }
                                    name={data.name || 'Customer'}
                                    size="md"
                                    cropShape="rect"
                                    onSelect={(file) => {
                                        setData('logo', file);
                                        setData('remove_logo', !file);
                                    }}
                                />
                                <p className="text-muted-foreground max-w-56 text-xs leading-relaxed">
                                    Square works best — it is shown small on the
                                    public card. Without a logo the card falls
                                    back to the institution's initials.
                                </p>
                            </div>
                            {errors.logo && (
                                <p className="text-destructive text-xs">
                                    {errors.logo}
                                </p>
                            )}
                        </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>

                            {status === 'draft' && (
                                <Button
                                    type="button"
                                    variant="outline"
                                    size="sm"
                                    disabled={processing}
                                    className="w-full"
                                    onClick={() =>
                                        setData(
                                            'published_at',
                                            new Date(
                                                Date.now() -
                                                    new Date().getTimezoneOffset() *
                                                        60000,
                                            )
                                                .toISOString()
                                                .substring(0, 16),
                                        )
                                    }
                                >
                                    Publish now
                                </Button>
                            )}

                            <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/customers"
                                    className="text-muted-foreground hover:text-foreground py-1 text-center text-sm transition-colors"
                                >
                                    Cancel
                                </Link>
                            </div>
                        </Card>

                        <Card title="Card preview">
                            <div className="border-border bg-card flex flex-col rounded-2xl border p-5">
                                <div className="flex items-center gap-3">
                                    {previewLogo ? (
                                        <div className="border-border bg-background flex h-11 w-11 shrink-0 items-center justify-center overflow-hidden rounded-xl border p-1">
                                            <img
                                                src={previewLogo}
                                                alt=""
                                                className="max-h-full max-w-full rounded-lg object-contain"
                                            />
                                        </div>
                                    ) : (
                                        <div className="bg-primary/10 flex h-11 w-11 shrink-0 items-center justify-center rounded-xl">
                                            <span className="text-primary text-sm font-bold">
                                                {initials(data.name) || '?'}
                                            </span>
                                        </div>
                                    )}
                                    <div className="min-w-0 flex-1">
                                        <p className="text-foreground truncate text-sm font-semibold">
                                            {data.name || 'Institution name'}
                                        </p>
                                        {data.sector && (
                                            <p className="text-muted-foreground truncate text-xs">
                                                {data.sector}
                                            </p>
                                        )}
                                    </div>
                                    {data.website && (
                                        <span className="border-border text-muted-foreground flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border">
                                            <ArrowUpRight className="h-3.5 w-3.5" />
                                        </span>
                                    )}
                                </div>
                                {data.description && (
                                    <p className="text-muted-foreground mt-3 line-clamp-3 text-xs leading-relaxed">
                                        {data.description}
                                    </p>
                                )}
                                {(data.location ||
                                    data.country ||
                                    data.since_year) && (
                                    <div className="mt-4">
                                        <div className="border-border flex items-center justify-between gap-2 border-t pt-3">
                                            <span className="text-muted-foreground flex min-w-0 items-center gap-1 text-xs">
                                                {(data.location ||
                                                    data.country) && (
                                                    <>
                                                        <MapPin className="h-3 w-3 shrink-0" />
                                                        <span className="truncate">
                                                            {[
                                                                data.location,
                                                                data.country,
                                                            ]
                                                                .filter(Boolean)
                                                                .join(', ')}
                                                        </span>
                                                    </>
                                                )}
                                            </span>
                                            {data.since_year && (
                                                <span className="text-muted-foreground/70 shrink-0 text-[11px] font-medium">
                                                    Since {data.since_year}
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                )}
                            </div>
                            <p className="text-muted-foreground text-xs">
                                How this customer appears on the public
                                customers page.
                            </p>
                        </Card>
                    </div>
                </div>
            </form>
        </AdminLayout>
    );
}
