import ClientLayout from '@/Layouts/ClientLayout';
import { AppDetail, PageProps } from '@/types';
import { Head, useForm } from '@inertiajs/react';
import { Building2, Globe, Users } from 'lucide-react';
import { useState } from 'react';
import AppNav from './components/AppNav';

const ORG_TYPES = [
    {
        value: 'sacco',
        label: 'SACCO',
        description: 'Savings & Credit Co-operative',
    },
    {
        value: 'microfinance',
        label: 'Microfinance',
        description: 'Microfinance Institution (MFI)',
    },
    {
        value: 'bank',
        label: 'Bank',
        description: 'Commercial or Community Bank',
    },
    {
        value: 'insurance',
        label: 'Insurance',
        description: 'Insurance Company or MGA',
    },
    {
        value: 'other',
        label: 'Other',
        description: 'Other financial institution',
    },
] as const;

const COUNTRIES = [
    { code: 'KE', name: 'Kenya' },
    { code: 'UG', name: 'Uganda' },
    { code: 'TZ', name: 'Tanzania' },
    { code: 'RW', name: 'Rwanda' },
    { code: 'ET', name: 'Ethiopia' },
    { code: 'GH', name: 'Ghana' },
    { code: 'NG', name: 'Nigeria' },
    { code: 'ZA', name: 'South Africa' },
    { code: 'ZM', name: 'Zambia' },
    { code: 'ZW', name: 'Zimbabwe' },
    { code: 'MW', name: 'Malawi' },
    { code: 'MZ', name: 'Mozambique' },
    { code: 'Other', name: 'Other' },
];

function toSlug(value: string): string {
    return value
        .toLowerCase()
        .replace(/[^a-z0-9-]/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
}

type Props = PageProps<{
    app: AppDetail;
    domainSuffix: string;
}>;

export default function AppSettings({ app, domainSuffix }: Props) {
    const { data, setData, patch, processing, errors, isDirty } = useForm({
        name: app.name,
        country: app.country ?? 'KE',
        org_type: app.orgType ?? '',
        subdomain: app.subdomain ?? toSlug(app.name),
    });

    const [subdomainTouched, setSubdomainTouched] = useState(false);

    const subdomainValid =
        data.subdomain.length >= 3 &&
        /^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(data.subdomain);

    function submit(e: React.FormEvent) {
        e.preventDefault();
        patch(route('app.settings.update', { tenant: app.id }));
    }

    const portalPreview = `https://${data.subdomain}${domainSuffix}`;

    return (
        <ClientLayout title={`${app.name} — Settings`}>
            <Head title={`${app.name} — Settings`} />

            <AppNav app={app} />

            <div className="p-6 lg:p-8">
                <div className="mx-auto max-w-2xl">
                    <form onSubmit={submit} className="space-y-8">
                        {/* Organisation details section */}
                        <div className="pf-glass overflow-hidden">
                            <div className="border-border border-b px-5 py-4">
                                <div className="flex items-center gap-2">
                                    <Building2 className="text-muted-foreground h-4 w-4" />
                                    <p className="text-foreground text-sm font-semibold">
                                        Organisation details
                                    </p>
                                </div>
                            </div>

                            <div className="space-y-5 p-5">
                                {/* Name */}
                                <div className="space-y-1.5">
                                    <label className="text-foreground text-sm font-medium">
                                        Organisation name
                                        <span className="text-destructive ml-0.5">
                                            *
                                        </span>
                                    </label>
                                    <input
                                        type="text"
                                        value={data.name}
                                        onChange={(e) =>
                                            setData('name', e.target.value)
                                        }
                                        className="border-border bg-background text-foreground placeholder:text-muted-foreground dark:placeholder:text-muted-foreground/50 focus:ring-primary/30 w-full rounded-xl border px-4 py-2.5 text-sm outline-none focus:ring-2"
                                    />
                                    {errors.name && (
                                        <p className="text-destructive text-xs">
                                            {errors.name}
                                        </p>
                                    )}
                                </div>

                                {/* Country */}
                                <div className="space-y-1.5">
                                    <label className="text-foreground flex items-center gap-1.5 text-sm font-medium">
                                        <Globe className="text-muted-foreground h-3.5 w-3.5" />
                                        Country
                                    </label>
                                    <select
                                        value={data.country}
                                        onChange={(e) =>
                                            setData('country', e.target.value)
                                        }
                                        className="border-border bg-background text-foreground focus:ring-primary/30 w-full rounded-xl border px-4 py-2.5 text-sm outline-none focus:ring-2"
                                    >
                                        {COUNTRIES.map(({ code, name }) => (
                                            <option key={code} value={code}>
                                                {name}
                                            </option>
                                        ))}
                                    </select>
                                    {errors.country && (
                                        <p className="text-destructive text-xs">
                                            {errors.country}
                                        </p>
                                    )}
                                </div>

                                {/* Org type */}
                                <div className="space-y-2">
                                    <label className="text-foreground flex items-center gap-1.5 text-sm font-medium">
                                        <Users className="text-muted-foreground h-3.5 w-3.5" />
                                        Organisation type
                                    </label>
                                    <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
                                        {ORG_TYPES.map(
                                            ({ value, label, description }) => (
                                                <button
                                                    key={value}
                                                    type="button"
                                                    onClick={() =>
                                                        setData(
                                                            'org_type',
                                                            value,
                                                        )
                                                    }
                                                    className={`rounded-xl border px-4 py-3 text-left transition-all ${
                                                        data.org_type === value
                                                            ? 'border-primary bg-primary/5 ring-primary/30 ring-2'
                                                            : 'border-border hover:border-primary/40 hover:bg-muted/30'
                                                    }`}
                                                >
                                                    <p className="text-foreground text-sm font-medium">
                                                        {label}
                                                    </p>
                                                    <p className="text-muted-foreground mt-0.5 text-xs">
                                                        {description}
                                                    </p>
                                                </button>
                                            ),
                                        )}
                                    </div>
                                    {errors.org_type && (
                                        <p className="text-destructive text-xs">
                                            {errors.org_type}
                                        </p>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Subdomain section */}
                        <div className="pf-glass overflow-hidden">
                            <div className="border-border border-b px-5 py-4">
                                <div className="flex items-center gap-2">
                                    <Globe className="text-muted-foreground h-4 w-4" />
                                    <p className="text-foreground text-sm font-semibold">
                                        Subdomain
                                    </p>
                                </div>
                                <p className="text-muted-foreground dark:text-muted-foreground/70 mt-0.5 text-xs">
                                    Changing this will update your portal URL.
                                    Existing links using the old URL will stop
                                    working.
                                </p>
                            </div>

                            <div className="space-y-4 p-5">
                                <div className="border-border focus-within:ring-primary/30 flex overflow-hidden rounded-xl border focus-within:ring-2">
                                    <input
                                        type="text"
                                        value={data.subdomain}
                                        onChange={(e) => {
                                            setSubdomainTouched(true);
                                            setData(
                                                'subdomain',
                                                toSlug(e.target.value),
                                            );
                                        }}
                                        placeholder="yourorg"
                                        className="bg-background text-foreground placeholder:text-muted-foreground dark:placeholder:text-muted-foreground/50 min-w-0 flex-1 px-4 py-2.5 text-sm outline-none"
                                    />
                                    <span className="bg-muted/40 text-muted-foreground flex items-center border-l px-3 text-sm select-none">
                                        {domainSuffix}
                                    </span>
                                </div>

                                {errors.subdomain && (
                                    <p className="text-destructive text-xs">
                                        {errors.subdomain}
                                    </p>
                                )}

                                {subdomainTouched &&
                                    data.subdomain &&
                                    !subdomainValid && (
                                        <p className="text-xs text-amber-600 dark:text-amber-400">
                                            Must be 3+ characters, lowercase,
                                            letters/numbers/hyphens only.
                                        </p>
                                    )}

                                <div className="bg-muted/30 border-border rounded-xl border p-3">
                                    <p className="text-muted-foreground mb-1 text-[10px] font-medium tracking-wider uppercase">
                                        Portal URL preview
                                    </p>
                                    <p className="text-foreground font-mono text-sm font-semibold break-all">
                                        {portalPreview}
                                    </p>
                                </div>
                            </div>
                        </div>

                        {/* Save */}
                        <div className="flex justify-end">
                            <button
                                type="submit"
                                disabled={
                                    processing ||
                                    !isDirty ||
                                    !data.name ||
                                    !data.org_type ||
                                    !subdomainValid
                                }
                                className="pf-btn px-6 py-2.5 text-sm disabled:cursor-not-allowed disabled:opacity-50"
                            >
                                {processing ? 'Saving…' : 'Save settings'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </ClientLayout>
    );
}
