/* The owner's business settings. */
import { useForm } from '@inertiajs/react';
import type { FormEvent } from 'react';
import { Save } from 'lucide-react';
import ShopLayout from '../../layouts/ShopLayout';
import BusinessFields from '../../components/BusinessFields';
import BrandingCard from '../../components/BrandingCard';
import { Button, Card, PageHeader, Toggle } from '../../components/ui';

type Settings = { name: string; type: string; currency: string; opensAt: string; closesAt: string; phone: string; staffCanChangePrice: boolean; requireShift: boolean; loansEnabled: boolean; balesEnabled: boolean; dayTotalEnabled: boolean; locale: 'en' | 'ny';
    brandColor: string; logoUrl: string | null; initials: string };

export default function SettingsPage({ settings, types, currencies, owedNow }: { settings: Settings; types: Record<string, string>; currencies: Record<string, string>; owedNow: string | null }) {
    const form = useForm({
        name: settings.name, type: settings.type, currency: settings.currency, opens_at: settings.opensAt, closes_at: settings.closesAt,
        staff_can_change_price: settings.staffCanChangePrice, require_shift: settings.requireShift, loans_enabled: settings.loansEnabled, bales_enabled: settings.balesEnabled, day_total_enabled: settings.dayTotalEnabled, locale: settings.locale,
    });
    const submit = (e: FormEvent) => { e.preventDefault(); form.put(route('settings.update'), { preserveScroll: true }); };

    return (
        <ShopLayout title="Settings">
            <PageHeader title="Business settings" />
            {/* saved on its own (a colour and a picture), apart from the settings form below */}
            <div className="mb-4">
                <BrandingCard name={settings.name} brandColor={settings.brandColor} logoUrl={settings.logoUrl} initials={settings.initials} />
            </div>
            <form onSubmit={submit} noValidate className="space-y-4">
                <Card>
                    <BusinessFields form={form} types={types} currencies={currencies} />
                    {form.data.currency !== settings.currency && (
                        <p className="mt-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-900">Changing the currency only changes how amounts are shown. Prices are not converted.</p>
                    )}
                </Card>
                <Card className={form.data.day_total_enabled ? 'border-emerald-200' : ''}>
                    <div className="flex items-center justify-between gap-3">
                        <div>
                            <p className="text-sm font-bold text-ink">Record the day’s money in one amount {form.data.day_total_enabled ? 'ON' : 'OFF'}</p>
                            <p className="text-xs text-muted">For counting the money at the end of the day (barbershops, kaunjika): one amount and Save, “Spent today” buttons, and a Sales page of money in and out.</p>
                        </div>
                        <Toggle checked={form.data.day_total_enabled} onChange={(v) => form.setData('day_total_enabled', v)} label="Record the day's money in one amount" />
                    </div>
                </Card>
                <Card className={form.data.bales_enabled ? 'border-emerald-200' : ''}>
                    <div className="flex items-center justify-between gap-3">
                        <div>
                            <p className="text-sm font-bold text-ink">Buy stock in bales (kaunjika) {form.data.bales_enabled ? 'ON' : 'OFF'}</p>
                            <p className="text-xs text-muted">For second-hand clothes and other stock bought as one lot: a Bales page shows what each bale made.</p>
                        </div>
                        <Toggle checked={form.data.bales_enabled} onChange={(v) => form.setData('bales_enabled', v)} label="Buy stock in bales" />
                    </div>
                </Card>
                <Card className={form.data.loans_enabled ? 'border-emerald-200' : ''}>
                    <div className="flex items-center justify-between gap-3">
                        <div>
                            <p className="text-sm font-bold text-ink">Customer loans (sell on credit) {form.data.loans_enabled ? 'ON' : 'OFF'}</p>
                            <p className="text-xs text-muted">On: a Customers tab, “Credit (pay later)” at the till, loan records and SMS reminders. Off: none of these show, for businesses that don’t give goods to pay later.</p>
                        </div>
                        <Toggle checked={form.data.loans_enabled} onChange={(v) => form.setData('loans_enabled', v)} label="Customer loans" />
                    </div>
                    {!form.data.loans_enabled && settings.loansEnabled && owedNow && (
                        <p className="mt-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-900">Customers still owe you {owedNow}. Nothing is deleted: their records come back when you switch loans on again. While off, no reminders are sent.</p>
                    )}
                </Card>
                <Card>
                    <div className="mb-4 flex items-center justify-between gap-3 border-b border-line pb-4">
                        <div>
                            <p className="text-sm font-bold text-ink">A shift must be open to sell</p>
                            <p className="text-xs text-muted">Each person opens a shift with the cash in the till and counts it at the end. Sales entered later, or made offline, never wait for a shift.</p>
                        </div>
                        <Toggle checked={form.data.require_shift} onChange={(v) => form.setData('require_shift', v)} label="A shift must be open to sell" />
                    </div>
                    <div className="mb-4 border-b border-line pb-4">
                        <p className="mb-2 text-sm font-bold text-ink">Language / Chiyankhulo</p>
                        <div className="grid grid-cols-2 gap-2">
                            {([['en', 'English'], ['ny', 'Chichewa']] as const).map(([k, v]) => (
                                <button key={k} type="button" onClick={() => form.setData('locale', k)} className={`rounded-xl border-2 px-3 py-2.5 text-sm font-bold ${form.data.locale === k ? 'border-brand bg-brand/[0.06] text-brand' : 'border-line text-ink-2'}`}>{v}</button>
                            ))}
                        </div>
                        <p className="mt-1.5 text-xs text-muted">For everyone in the business. Each person can choose their own under My profile.</p>
                    </div>
                    <div className="flex items-center justify-between gap-3">
                        <div>
                            <p className="text-sm font-bold text-ink">Staff can change prices at the till</p>
                            <p className="text-xs text-muted">For bargaining. Changed prices show in the sale. You can always change them.</p>
                        </div>
                        <Toggle checked={form.data.staff_can_change_price} onChange={(v) => form.setData('staff_can_change_price', v)} label="Staff can change prices" />
                    </div>
                </Card>
                <Button type="submit" size="lg" icon={Save} className="w-full sm:w-auto" disabled={form.processing || !form.isDirty}>{form.isDirty ? 'Save settings' : 'Saved'}</Button>
            </form>
        </ShopLayout>
    );
}
