import AdminLayout from '@/Layouts/AdminLayout';
import { ImageUploader } from '@/components/ImageUploader';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { api } from '@/lib/api';
import { parseServerDate } from '@/lib/date';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { format } from 'date-fns';
import {
    AtSign,
    Briefcase,
    Building2,
    Calendar,
    CheckCircle2,
    Clock,
    Globe,
    KeyRound,
    Loader2,
    Phone,
    Save,
    Shield,
    ShieldCheck,
} from 'lucide-react';

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

interface Profile {
    id: string;
    name: string;
    email: string;
    phone: string | null;
    job_title: string | null;
    department: string | null;
    timezone: string;
    avatar_url: string | null;
    role: string | null;
    status: string;
    last_login_at: string | null;
    email_verified_at: string | null;
    created_at: string;
}

interface Props {
    profile: Profile;
}

// ── Constants ─────────────────────────────────────────────────────────────────

const TIMEZONES = [
    'Africa/Nairobi',
    'Africa/Lagos',
    'Africa/Cairo',
    'Africa/Johannesburg',
    'UTC',
    'Europe/London',
    'Europe/Paris',
    'Asia/Dubai',
    'Asia/Kolkata',
    'America/New_York',
    'America/Los_Angeles',
];

// ── Form field ────────────────────────────────────────────────────────────────

function Field({
    label,
    hint,
    error,
    children,
    required,
}: {
    label: string;
    hint?: string;
    error?: string;
    children: React.ReactNode;
    required?: boolean;
}) {
    return (
        <div className="space-y-1.5">
            <label className="text-foreground text-sm font-medium">
                {label}
                {required && <span className="text-destructive ml-0.5">*</span>}
            </label>
            {children}
            {hint && !error && (
                <p className="text-muted-foreground text-xs">{hint}</p>
            )}
            {error && <p className="text-destructive text-xs">{error}</p>}
        </div>
    );
}

// ── Meta row ──────────────────────────────────────────────────────────────────

function MetaRow({
    icon: Icon,
    label,
    value,
}: {
    icon: React.ComponentType<{ className?: string }>;
    label: string;
    value: React.ReactNode;
}) {
    return (
        <div className="flex items-center gap-3 py-2">
            <div className="bg-muted flex h-7 w-7 shrink-0 items-center justify-center rounded-full">
                <Icon className="text-muted-foreground h-3.5 w-3.5" />
            </div>
            <div className="min-w-0">
                <p className="text-muted-foreground text-[10px]">{label}</p>
                <p className="text-foreground truncate text-sm">{value}</p>
            </div>
        </div>
    );
}

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

export default function ProfileIndex({ profile }: Props) {
    const { props } = usePage<PageProps>();
    const success = (props.flash as { success?: string } | undefined)?.success;

    const { data, setData, put, processing, errors } = useForm({
        name: profile.name,
        email: profile.email,
        phone: profile.phone ?? '',
        job_title: profile.job_title ?? '',
        department: profile.department ?? '',
        timezone: profile.timezone,
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        put('/admin/profile');
    };

    const initials = profile.name
        .split(' ')
        .map((w) => w[0])
        .join('')
        .slice(0, 2)
        .toUpperCase();

    return (
        <AdminLayout title="Profile">
            <Head title="Profile" />

            {/* Hero */}
            <div className="border-border bg-background/60 border-b px-6 py-5 backdrop-blur-sm">
                <div className="flex items-center gap-4">
                    {profile.avatar_url ? (
                        <img
                            src={profile.avatar_url}
                            alt={profile.name}
                            className="ring-border h-12 w-12 rounded-full object-cover ring-2"
                        />
                    ) : (
                        <div className="bg-primary/10 text-primary ring-border flex h-12 w-12 shrink-0 items-center justify-center rounded-full font-bold ring-2">
                            {initials}
                        </div>
                    )}
                    <div>
                        <h1 className="text-foreground text-lg font-bold">
                            {profile.name}
                        </h1>
                        <div className="mt-0.5 flex flex-wrap items-center gap-2">
                            {profile.role && (
                                <span className="bg-muted text-foreground rounded-full px-2 py-0.5 font-mono text-[10px] font-semibold">
                                    {profile.role}
                                </span>
                            )}
                            <span
                                className={cn(
                                    'rounded-full px-2 py-0.5 text-[10px] font-semibold',
                                    profile.status === 'active'
                                        ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/25 dark:text-emerald-400'
                                        : 'bg-muted text-muted-foreground',
                                )}
                            >
                                {profile.status}
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div className="flex flex-col gap-6 p-6 lg:flex-row lg:items-start lg:p-8">
                {/* ── Left column: avatar + account meta ── */}
                <div className="w-full space-y-5 lg:w-64 lg:shrink-0">
                    {/* Avatar */}
                    <div className="pf-glass p-5">
                        <ImageUploader
                            url={profile.avatar_url}
                            name={profile.name}
                            size="lg"
                            onUpload={(file) => {
                                const form = new FormData();
                                form.append('avatar', file);
                                return api.upload<{ avatar_url: string }>(
                                    '/admin/profile/avatar',
                                    form,
                                );
                            }}
                            onRemove={() => api.delete('/admin/profile/avatar')}
                        />
                    </div>

                    {/* Account meta */}
                    <div className="pf-glass p-4">
                        <p className="text-muted-foreground dark:text-muted-foreground/65 mb-2 text-[10px] font-bold tracking-widest uppercase">
                            Account
                        </p>
                        <MetaRow
                            icon={Shield}
                            label="Role"
                            value={
                                profile.role ? (
                                    <span className="font-mono">
                                        {profile.role}
                                    </span>
                                ) : (
                                    <span className="text-muted-foreground italic">
                                        None
                                    </span>
                                )
                            }
                        />
                        <MetaRow
                            icon={Calendar}
                            label="Member since"
                            value={format(
                                parseServerDate(profile.created_at),
                                'dd MMM yyyy',
                            )}
                        />
                        <MetaRow
                            icon={Clock}
                            label="Last login"
                            value={
                                profile.last_login_at ? (
                                    format(
                                        parseServerDate(profile.last_login_at),
                                        'dd MMM yyyy, HH:mm',
                                    )
                                ) : (
                                    <span className="text-muted-foreground italic">
                                        Never
                                    </span>
                                )
                            }
                        />
                        <MetaRow
                            icon={ShieldCheck}
                            label="Email verified"
                            value={
                                profile.email_verified_at ? (
                                    format(
                                        parseServerDate(
                                            profile.email_verified_at,
                                        ),
                                        'dd MMM yyyy',
                                    )
                                ) : (
                                    <span className="text-amber-600 dark:text-amber-400">
                                        Not verified
                                    </span>
                                )
                            }
                        />
                    </div>

                    {/* Change password link */}
                    <Link
                        href="/admin/settings/security"
                        className="pf-glass flex items-center gap-3 p-4 transition-opacity hover:opacity-80"
                    >
                        <div className="bg-primary/10 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg">
                            <KeyRound className="text-primary h-4 w-4" />
                        </div>
                        <div>
                            <p className="text-foreground text-sm font-medium">
                                Change password
                            </p>
                            <p className="text-muted-foreground text-xs">
                                Security settings
                            </p>
                        </div>
                    </Link>
                </div>

                {/* ── Right column: edit form ── */}
                <div className="min-w-0 flex-1">
                    {success && (
                        <div className="mb-4 flex items-center gap-2 rounded-lg bg-emerald-50 px-4 py-2.5 text-sm text-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-400">
                            <CheckCircle2 className="h-4 w-4 shrink-0" />
                            {success}
                        </div>
                    )}

                    <form onSubmit={handleSubmit}>
                        <div className="pf-glass space-y-6 p-6">
                            <div>
                                <h3 className="text-foreground text-sm font-semibold">
                                    Personal information
                                </h3>
                                <p className="text-muted-foreground mt-0.5 text-xs">
                                    Update your name, contact details, and work
                                    info.
                                </p>
                            </div>

                            <div className="grid gap-4 sm:grid-cols-2">
                                <Field
                                    label="Full name"
                                    error={errors.name}
                                    required
                                >
                                    <Input
                                        value={data.name}
                                        onChange={(e) =>
                                            setData('name', e.target.value)
                                        }
                                        className={cn(
                                            errors.name && 'border-destructive',
                                        )}
                                        autoComplete="name"
                                    />
                                </Field>

                                <Field
                                    label="Email address"
                                    error={errors.email}
                                    required
                                >
                                    <div className="relative">
                                        <AtSign className="text-muted-foreground absolute top-1/2 left-3 h-3.5 w-3.5 -translate-y-1/2" />
                                        <Input
                                            type="email"
                                            value={data.email}
                                            onChange={(e) =>
                                                setData('email', e.target.value)
                                            }
                                            className={cn(
                                                'pl-9',
                                                errors.email &&
                                                    'border-destructive',
                                            )}
                                            autoComplete="email"
                                        />
                                    </div>
                                </Field>

                                <Field label="Phone" error={errors.phone}>
                                    <div className="relative">
                                        <Phone className="text-muted-foreground absolute top-1/2 left-3 h-3.5 w-3.5 -translate-y-1/2" />
                                        <Input
                                            type="tel"
                                            value={data.phone}
                                            onChange={(e) =>
                                                setData('phone', e.target.value)
                                            }
                                            className={cn(
                                                'pl-9',
                                                errors.phone &&
                                                    'border-destructive',
                                            )}
                                            placeholder="+254 7xx xxx xxx"
                                        />
                                    </div>
                                </Field>

                                <Field
                                    label="Timezone"
                                    error={errors.timezone}
                                    required
                                >
                                    <div className="relative">
                                        <Globe className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 z-10 h-3.5 w-3.5 -translate-y-1/2" />
                                        <Select
                                            value={data.timezone}
                                            onValueChange={(v) =>
                                                setData('timezone', v)
                                            }
                                        >
                                            <SelectTrigger
                                                className={cn(
                                                    'pl-9',
                                                    errors.timezone &&
                                                        'border-destructive',
                                                )}
                                            >
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {TIMEZONES.map((tz) => (
                                                    <SelectItem
                                                        key={tz}
                                                        value={tz}
                                                    >
                                                        {tz}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </Field>
                            </div>

                            <div className="border-border border-t" />

                            <div>
                                <h3 className="text-foreground text-sm font-semibold">
                                    Work
                                </h3>
                            </div>

                            <div className="grid gap-4 sm:grid-cols-2">
                                <Field
                                    label="Job title"
                                    error={errors.job_title}
                                >
                                    <div className="relative">
                                        <Briefcase className="text-muted-foreground absolute top-1/2 left-3 h-3.5 w-3.5 -translate-y-1/2" />
                                        <Input
                                            value={data.job_title}
                                            onChange={(e) =>
                                                setData(
                                                    'job_title',
                                                    e.target.value,
                                                )
                                            }
                                            className={cn(
                                                'pl-9',
                                                errors.job_title &&
                                                    'border-destructive',
                                            )}
                                            placeholder="e.g. Operations Lead"
                                        />
                                    </div>
                                </Field>

                                <Field
                                    label="Department"
                                    error={errors.department}
                                >
                                    <div className="relative">
                                        <Building2 className="text-muted-foreground absolute top-1/2 left-3 h-3.5 w-3.5 -translate-y-1/2" />
                                        <Input
                                            value={data.department}
                                            onChange={(e) =>
                                                setData(
                                                    'department',
                                                    e.target.value,
                                                )
                                            }
                                            className={cn(
                                                'pl-9',
                                                errors.department &&
                                                    'border-destructive',
                                            )}
                                            placeholder="e.g. Product"
                                        />
                                    </div>
                                </Field>
                            </div>

                            <div className="border-border flex items-center justify-between border-t pt-5">
                                <p className="text-muted-foreground text-xs">
                                    Role and status can only be changed by
                                    another super admin.
                                </p>
                                <Button
                                    type="submit"
                                    disabled={processing}
                                    size="sm"
                                    className="gap-2"
                                >
                                    {processing ? (
                                        <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                    ) : (
                                        <Save className="h-3.5 w-3.5" />
                                    )}
                                    Save changes
                                </Button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </AdminLayout>
    );
}
