/* The platform admin adds a business: its details, the owner's sign-in (phone + PIN to pass on), and billing. */
import { useForm } from '@inertiajs/react';
import type { FormEvent } from 'react';
import { Building2, CreditCard, Plus, UserRound } from 'lucide-react';
import PlatformLayout from '../../layouts/PlatformLayout';
import BusinessFields from '../../components/BusinessFields';
import PinInput from '../../components/PinInput';
import { Button, Card, CardHeader, ErrorSummary, Field, Input, PageHeader, Toggle } from '../../components/ui';

type Props = {
    types: Record<string, string>;
    currencies: Record<string, string>;
    defaults: { monthly_fee: string; trial_days: string; sms_credits: string };
    platformCurrency: string;
};

export default function BusinessCreate({ types, currencies, defaults, platformCurrency }: Props) {
    const form = useForm({
        name: '', type: 'shop', currency: 'MWK', opens_at: '', closes_at: '', loans_enabled: false,
        owner_name: '', owner_phone: '', owner_pin: '',
        billing_enabled: true, monthly_fee: defaults.monthly_fee, trial_days: defaults.trial_days, sms_credits: defaults.sms_credits,
    });
    const err = form.errors as Record<string, string | undefined>;
    const submit = (e: FormEvent) => { e.preventDefault(); form.post(route('platform.businesses.store')); };

    return (
        <PlatformLayout title="Add a business">
            <PageHeader title="Add a business" subtitle="For someone you are setting up yourself. They can also sign up on their own." back={{ href: route('platform.businesses.index'), label: 'Businesses' }} />
            <ErrorSummary errors={err} className="mb-4" />
            <form onSubmit={submit} noValidate className="grid max-w-5xl gap-6 lg:grid-cols-2">
                <Card>
                    <CardHeader icon={Building2} title="The business" />
                    <div className="mt-5">
                        <BusinessFields form={form} types={types} currencies={currencies} />
                        <div className="mt-5 flex items-center justify-between gap-3 rounded-xl border border-line p-3">
                            <div><p className="text-sm font-bold text-ink">Customer loans (sell on credit)</p><p className="text-xs text-muted">Customers tab, credit at the till, SMS reminders.</p></div>
                            <Toggle checked={form.data.loans_enabled} onChange={(v) => form.setData('loans_enabled', v)} label="Customer loans" />
                        </div>
                    </div>
                </Card>

                <div className="space-y-6">
                    <Card>
                        <CardHeader icon={UserRound} title="The owner" subtitle="They sign in with this phone number and PIN. Tell them the PIN; they can change it later." />
                        <div className="mt-5 space-y-4">
                            <Field label="Owner's name" htmlFor="o-name" error={err.owner_name} required>
                                <Input id="o-name" value={form.data.owner_name} onChange={(e) => form.setData('owner_name', e.target.value)} invalid={!!err.owner_name} />
                            </Field>
                            <Field label="Owner's phone number" htmlFor="o-phone" error={err.owner_phone_e164 ?? err.owner_phone} required>
                                <Input id="o-phone" type="tel" inputMode="tel" placeholder="0991 234 567" value={form.data.owner_phone} onChange={(e) => form.setData('owner_phone', e.target.value)} invalid={!!(err.owner_phone_e164 ?? err.owner_phone)} />
                            </Field>
                            <Field label="First PIN" htmlFor="o-pin" error={err.owner_pin} required hint="At least 4 digits.">
                                <PinInput id="o-pin" autoComplete="new-password" value={form.data.owner_pin} onChange={(v) => form.setData('owner_pin', v)} invalid={!!err.owner_pin} />
                            </Field>
                        </div>
                    </Card>

                    <Card>
                        <CardHeader icon={CreditCard} title="Billing" />
                        <div className="mt-5 space-y-4">
                            <div className="flex items-center justify-between gap-3 rounded-xl border border-line p-3">
                                <div>
                                    <p className="text-sm font-bold text-ink">Billing {form.data.billing_enabled ? 'on' : 'off'}</p>
                                    <p className="text-xs text-muted">{form.data.billing_enabled ? 'They pay the monthly fee after the free trial.' : 'Free: never asked to pay, never locks.'}</p>
                                </div>
                                <Toggle checked={form.data.billing_enabled} onChange={(v) => form.setData('billing_enabled', v)} label="Billing on" />
                            </div>
                            <div className="grid grid-cols-3 gap-3">
                                <Field label={`Fee / month (${platformCurrency})`} htmlFor="b-fee" error={err.fee_minor}>
                                    <Input id="b-fee" inputMode="decimal" value={form.data.monthly_fee} onChange={(e) => form.setData('monthly_fee', e.target.value)} disabled={!form.data.billing_enabled} />
                                </Field>
                                <Field label="Free trial (days)" htmlFor="b-trial" error={err.trial_days}>
                                    <Input id="b-trial" inputMode="numeric" value={form.data.trial_days} onChange={(e) => form.setData('trial_days', e.target.value)} disabled={!form.data.billing_enabled} />
                                </Field>
                                <Field label="Free SMS" htmlFor="b-sms" error={err.sms_credits}>
                                    <Input id="b-sms" inputMode="numeric" value={form.data.sms_credits} onChange={(e) => form.setData('sms_credits', e.target.value)} />
                                </Field>
                            </div>
                        </div>
                    </Card>

                    <Button type="submit" size="lg" icon={Plus} className="w-full" disabled={form.processing}>{form.processing ? 'Adding…' : 'Add business'}</Button>
                </div>
            </form>
        </PlatformLayout>
    );
}
