import { Form, Head } from '@inertiajs/react';
import { useState } from 'react';
import SavingsPlanController from '@/actions/App/Http/Controllers/SavingsPlanController';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import NairaInput from '@/components/member/naira-input';
import { savingsTypeStyle } from '@/components/member/savings-type-style';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import { create, index } from '@/routes/savings';
import type { SelectOption } from '@/types';

type TypeOption = SelectOption & { description: string; rule: string };

const selectClasses =
    'h-10 w-full rounded-md border border-input bg-white px-3 text-sm text-ink shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15';

export default function SavingsCreate({
    types,
    frequencies,
    today,
}: {
    types: TypeOption[];
    frequencies: SelectOption[];
    today: string;
}) {
    const [selectedType, setSelectedType] = useState(types[0]?.value ?? '');
    const [targetAmount, setTargetAmount] = useState('');
    const [contributionAmount, setContributionAmount] = useState('');
    const [frequency, setFrequency] = useState('monthly');
    const target = Number(targetAmount);
    const contribution = Number(contributionAmount);
    const contributionsNeeded =
        target > 0 && contribution > 0 && contribution <= target
            ? Math.ceil(target / contribution)
            : null;
    const frequencyLabel =
        frequencies
            .find((option) => option.value === frequency)
            ?.label.toLowerCase() ?? '';
    const periodWord = (
        { daily: 'day', weekly: 'week', monthly: 'month' } as Record<
            string,
            string
        >
    )[frequency];
    const selectedTypeOption = types.find(
        (type) => type.value === selectedType,
    );

    return (
        <>
            <Head title="New savings plan" />

            <MemberPage
                title="New savings plan"
                description="No hidden charges. Your money stays yours."
            >
                <Form
                    {...SavingsPlanController.store.form()}
                    className="grid max-w-3xl gap-6"
                >
                    {({ processing, errors }) => (
                        <>
                            <fieldset className="grid content-start gap-2">
                                <legend className="mb-2 text-sm font-semibold text-ink-700">
                                    Plan type
                                </legend>
                                <div className="grid grid-cols-3 gap-2 sm:grid-cols-5">
                                    {types.map((type) => {
                                        const style = savingsTypeStyle(
                                            type.rule,
                                        );
                                        const isSelected =
                                            selectedType === type.value;

                                        return (
                                            <label
                                                key={type.value}
                                                className={cn(
                                                    'flex cursor-pointer flex-col items-center gap-1.5 rounded-landing border bg-white px-2 py-3 text-center transition-colors has-focus-visible:ring-2 has-focus-visible:ring-highlight',
                                                    isSelected
                                                        ? 'border-brand ring-2 ring-brand/15'
                                                        : 'border-surface-200 hover:border-brand/40',
                                                )}
                                            >
                                                <input
                                                    type="radio"
                                                    name="type"
                                                    value={type.value}
                                                    checked={isSelected}
                                                    onChange={() =>
                                                        setSelectedType(
                                                            type.value,
                                                        )
                                                    }
                                                    className="sr-only"
                                                />
                                                <span
                                                    className={cn(
                                                        'flex size-8 items-center justify-center rounded-landing',
                                                        style.tone,
                                                    )}
                                                >
                                                    <style.icon className="size-4" />
                                                </span>
                                                <span className="text-xs leading-tight font-semibold text-ink">
                                                    {type.label}
                                                </span>
                                            </label>
                                        );
                                    })}
                                </div>
                                {selectedTypeOption && (
                                    <p className="text-xs text-ink-500">
                                        {selectedTypeOption.description}
                                    </p>
                                )}
                                <InputError message={errors.type} />
                            </fieldset>

                            <div className="grid gap-5 rounded-landing-lg border border-surface-200 bg-white p-5 sm:grid-cols-2 sm:p-6">
                                <div className="grid content-start gap-2 sm:col-span-2">
                                    <Label htmlFor="name" required>
                                        Plan name
                                    </Label>
                                    <Input
                                        id="name"
                                        name="name"
                                        required
                                        maxLength={80}
                                        placeholder="e.g. Amina's school fees"
                                    />
                                    <InputError message={errors.name} />
                                </div>

                                <div className="grid content-start gap-2">
                                    <Label htmlFor="target_amount" required>
                                        Target amount
                                    </Label>
                                    <NairaInput
                                        id="target_amount"
                                        name="target_amount"
                                        required
                                        value={targetAmount}
                                        onChange={(event) =>
                                            setTargetAmount(
                                                event.target.value.replace(
                                                    /[^\d.]/g,
                                                    '',
                                                ),
                                            )
                                        }
                                        placeholder="450000"
                                        aria-invalid={
                                            errors.target_amount
                                                ? true
                                                : undefined
                                        }
                                    />
                                    <InputError
                                        message={errors.target_amount}
                                    />
                                </div>

                                <div className="grid content-start gap-2">
                                    <Label
                                        htmlFor="contribution_amount"
                                        required
                                    >
                                        Contribution amount
                                    </Label>
                                    <NairaInput
                                        id="contribution_amount"
                                        name="contribution_amount"
                                        required
                                        value={contributionAmount}
                                        onChange={(event) =>
                                            setContributionAmount(
                                                event.target.value.replace(
                                                    /[^\d.]/g,
                                                    '',
                                                ),
                                            )
                                        }
                                        placeholder="25000"
                                        aria-invalid={
                                            errors.contribution_amount
                                                ? true
                                                : undefined
                                        }
                                    />
                                    <p className="text-xs text-ink-400">
                                        How much you put in each{' '}
                                        {periodWord ?? 'time'}.
                                    </p>
                                    <InputError
                                        message={errors.contribution_amount}
                                    />
                                </div>

                                <div className="grid content-start gap-2">
                                    <Label htmlFor="frequency">How often</Label>
                                    <select
                                        id="frequency"
                                        name="frequency"
                                        value={frequency}
                                        onChange={(event) =>
                                            setFrequency(event.target.value)
                                        }
                                        className={selectClasses}
                                    >
                                        {frequencies.map((option) => (
                                            <option
                                                key={option.value}
                                                value={option.value}
                                            >
                                                {option.label}
                                            </option>
                                        ))}
                                    </select>
                                    <InputError message={errors.frequency} />
                                </div>

                                <div className="flex items-end">
                                    <p className="w-full rounded-landing bg-surface-50 px-3 py-2.5 text-xs text-ink-500">
                                        {contributionsNeeded ? (
                                            <>
                                                About{' '}
                                                <strong className="font-semibold text-ink">
                                                    {contributionsNeeded}{' '}
                                                    {frequencyLabel}
                                                </strong>{' '}
                                                contributions of ₦
                                                {contribution.toLocaleString(
                                                    'en-NG',
                                                )}{' '}
                                                to reach ₦
                                                {target.toLocaleString('en-NG')}
                                                .
                                            </>
                                        ) : (
                                            'Enter a target and contribution to see how long it will take.'
                                        )}
                                    </p>
                                </div>

                                <div className="grid content-start gap-2">
                                    <Label htmlFor="start_date" required>
                                        Start date
                                    </Label>
                                    <Input
                                        id="start_date"
                                        name="start_date"
                                        type="date"
                                        required
                                        min={today}
                                        defaultValue={today}
                                    />
                                    <InputError message={errors.start_date} />
                                </div>

                                <div className="grid content-start gap-2">
                                    <Label htmlFor="maturity_date" required>
                                        Maturity date
                                    </Label>
                                    <Input
                                        id="maturity_date"
                                        name="maturity_date"
                                        type="date"
                                        required
                                        min={today}
                                    />
                                    <InputError
                                        message={errors.maturity_date}
                                    />
                                </div>

                                <div className="flex items-start gap-3 sm:col-span-2">
                                    <Checkbox
                                        id="auto_debit"
                                        name="auto_debit"
                                        value="1"
                                        className="mt-0.5"
                                    />
                                    <Label
                                        htmlFor="auto_debit"
                                        className="leading-snug font-normal text-ink-700"
                                    >
                                        Save automatically — move the amount
                                        from my wallet on each due date
                                    </Label>
                                </div>
                            </div>

                            <div>
                                <Button disabled={processing}>
                                    Create plan
                                </Button>
                            </div>
                        </>
                    )}
                </Form>
            </MemberPage>
        </>
    );
}

SavingsCreate.layout = {
    breadcrumbs: [
        { title: 'Savings', href: index() },
        { title: 'New plan', href: create() },
    ],
};
