import { Form, Head, Link } from '@inertiajs/react';
import {
    AlertTriangle,
    Camera,
    Info,
    ShieldAlert,
    Sun,
} from 'lucide-react';
import { useState } from 'react';
import InputError from '@/components/input-error';
import { TicketCard } from '@/components/ticket/ticket-ui';
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 { Spinner } from '@/components/ui/spinner';
import type { CustomerIssueCategory } from '@/types';

type JobOption = {
    value: number;
    label: string;
    note: string | null;
};

type Props = {
    categories: CustomerIssueCategory[];
    jobs: JobOption[];
    selectedJobId: number | null;
    contact: {
        name: string;
        phone: string | null;
        email: string | null;
    };
    support: {
        phone: string | null;
    };
};

const textareaClassName =
    'border-input min-h-32 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]';

const selectClassName =
    'border-input h-9 w-full rounded-md border bg-transparent px-3 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]';

export default function TicketCreate({
    categories,
    jobs,
    selectedJobId,
    contact,
    support,
}: Props) {
    const [category, setCategory] = useState<string>(categories[0]?.value ?? '');
    const [safety, setSafety] = useState(false);

    const chosen = categories.find((item) => item.value === category) ?? null;

    return (
        <>
            <Head title="Report an issue" />

            <div className="mx-auto w-full max-w-3xl">
                <div className="flex flex-wrap items-end justify-between gap-3">
                    <div>
                        <h1 className="text-2xl font-semibold tracking-tight">
                            Report an issue
                        </h1>
                        <p className="mt-1 text-sm text-muted-foreground">
                            Tell us what is happening. We already know your
                            details and your system.
                        </p>
                    </div>
                    <Button asChild variant="ghost" size="sm">
                        <Link href="/ticket/tickets">Cancel</Link>
                    </Button>
                </div>

                <div className="mt-5 flex items-start gap-2.5 rounded-xl border border-red-500/25 bg-red-500/[0.06] p-4 text-xs leading-relaxed text-red-800 dark:text-red-300">
                    <ShieldAlert className="mt-0.5 size-4 shrink-0" />
                    <p>
                        If the system is smoking, sparking, or you can smell
                        burning, stop here and call{' '}
                        <a href="tel:000" className="font-semibold underline">
                            000
                        </a>
                        . Keep everybody clear of the panels and the inverter.
                        Submit the report afterwards so we have it on record.
                    </p>
                </div>

                <Form
                    action="/ticket/tickets"
                    method="post"
                    className="mt-5 flex flex-col gap-5"
                >
                    {({ processing, errors }) => (
                        <>
                            <TicketCard title="What is wrong?">
                                <div className="grid gap-4">
                                    <div className="grid gap-2">
                                        <Label htmlFor="category">
                                            Closest match
                                        </Label>
                                        <select
                                            id="category"
                                            name="category"
                                            className={selectClassName}
                                            value={category}
                                            onChange={(event) =>
                                                setCategory(event.target.value)
                                            }
                                            required
                                        >
                                            {categories.map((item) => (
                                                <option
                                                    key={item.value}
                                                    value={item.value}
                                                >
                                                    {item.label}
                                                </option>
                                            ))}
                                        </select>
                                        {chosen ? (
                                            <p className="text-xs text-muted-foreground">
                                                {chosen.description}
                                            </p>
                                        ) : null}
                                        <InputError
                                            message={errors.category}
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="description">
                                            What have you noticed?
                                        </Label>
                                        <textarea
                                            id="description"
                                            name="description"
                                            className={textareaClassName}
                                            required
                                            minLength={10}
                                            maxLength={5000}
                                            placeholder="For example: the inverter light went red on Tuesday and the app has shown zero production since. Nothing has changed on the switchboard."
                                        />
                                        <p className="text-xs text-muted-foreground">
                                            When it started, what the display or
                                            app shows, and anything that
                                            changed before it — an error code
                                            in full is the most useful thing
                                            you can give us.
                                        </p>
                                        <InputError
                                            message={errors.description}
                                        />
                                    </div>

                                    {jobs.length > 0 ? (
                                        <div className="grid gap-2">
                                            <Label htmlFor="job_id">
                                                Which system?
                                            </Label>
                                            <select
                                                id="job_id"
                                                name="job_id"
                                                className={selectClassName}
                                                defaultValue={
                                                    selectedJobId ?? ''
                                                }
                                            >
                                                <option value="">
                                                    Not sure / another
                                                    property
                                                </option>
                                                {jobs.map((job) => (
                                                    <option
                                                        key={job.value}
                                                        value={job.value}
                                                    >
                                                        {job.label}
                                                        {job.note
                                                            ? ` (${job.note})`
                                                            : ''}
                                                    </option>
                                                ))}
                                            </select>
                                            <InputError
                                                message={errors.job_id}
                                            />
                                        </div>
                                    ) : null}

                                    <div className="rounded-xl bg-muted/50 p-3">
                                        <div className="flex items-start gap-2.5">
                                            <Checkbox
                                                id="safety_concern"
                                                name="safety_concern"
                                                checked={safety}
                                                onCheckedChange={(value) =>
                                                    setSafety(value === true)
                                                }
                                            />
                                            <div>
                                                <Label htmlFor="safety_concern">
                                                    I am worried about safety
                                                </Label>
                                                <p className="mt-1 text-xs text-muted-foreground">
                                                    Smoke, burning smell,
                                                    sparking, exposed wiring,
                                                    damaged panels or water
                                                    getting in. We triage these
                                                    first.
                                                </p>
                                            </div>
                                        </div>

                                        {safety ? (
                                            <p className="mt-3 flex items-start gap-2 rounded-lg bg-red-500/10 px-3 py-2 text-xs leading-relaxed text-red-800 dark:text-red-300">
                                                <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
                                                Keep clear of the system and, if
                                                it is safe to do so, turn off the
                                                inverter and the solar supply
                                                main switch. If there is fire,
                                                smoke or sparking, call 000
                                                first.
                                            </p>
                                        ) : null}
                                    </div>
                                </div>
                            </TicketCard>

                            <TicketCard
                                title="Who should we contact?"
                                description="Filled in from your account. Change anything that is wrong."
                            >
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <div className="grid gap-2 sm:col-span-2">
                                        <Label htmlFor="contact_name">
                                            Name
                                        </Label>
                                        <Input
                                            id="contact_name"
                                            name="contact_name"
                                            defaultValue={contact.name}
                                            required
                                        />
                                        <InputError
                                            message={errors.contact_name}
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="contact_phone">
                                            Phone
                                        </Label>
                                        <Input
                                            id="contact_phone"
                                            name="contact_phone"
                                            type="tel"
                                            defaultValue={contact.phone ?? ''}
                                            required
                                        />
                                        <InputError
                                            message={errors.contact_phone}
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="contact_email">
                                            Email
                                        </Label>
                                        <Input
                                            id="contact_email"
                                            name="contact_email"
                                            type="email"
                                            defaultValue={contact.email ?? ''}
                                            required
                                        />
                                        <InputError
                                            message={errors.contact_email}
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="preferred_contact">
                                            Best way to reach you
                                        </Label>
                                        <select
                                            id="preferred_contact"
                                            name="preferred_contact"
                                            className={selectClassName}
                                            defaultValue="phone"
                                        >
                                            <option value="phone">
                                                Phone call
                                            </option>
                                            <option value="sms">
                                                Text message
                                            </option>
                                            <option value="email">Email</option>
                                        </select>
                                        <InputError
                                            message={errors.preferred_contact}
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label htmlFor="best_time">
                                            Best time
                                        </Label>
                                        <Input
                                            id="best_time"
                                            name="best_time"
                                            placeholder="Weekdays after 4pm"
                                        />
                                        <InputError message={errors.best_time} />
                                    </div>

                                    <div className="flex items-start gap-2.5 sm:col-span-2">
                                        <Checkbox
                                            id="access_permitted"
                                            name="access_permitted"
                                            defaultChecked
                                            className="mt-0.5"
                                        />
                                        <div>
                                            <Label htmlFor="access_permitted">
                                                We can arrange access to the
                                                property
                                            </Label>
                                            <p className="mt-1 text-xs text-muted-foreground">
                                                Gate codes, dogs or a preferred
                                                day can go in the description.
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </TicketCard>

                            <TicketCard
                                title="Photos (optional, but they help)"
                                description="The inverter display, the error screen, the app, or the panels. Up to 6 photos or a PDF."
                            >
                                <div className="flex items-start gap-2.5 rounded-xl border border-dashed border-hairline p-4">
                                    <Camera className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
                                    <div className="w-full">
                                        <Input
                                            id="attachments"
                                            name="attachments[]"
                                            type="file"
                                            multiple
                                            accept="image/*,.pdf"
                                            className="h-auto py-1.5"
                                        />
                                        <p className="mt-1.5 text-xs text-muted-foreground">
                                            Photos taken on a phone are fine.
                                            10 MB each.
                                        </p>
                                        <InputError
                                            message={
                                                errors['attachments'] ??
                                                errors['attachments.0']
                                            }
                                        />
                                    </div>
                                </div>
                            </TicketCard>

                            <div className="flex flex-wrap items-center gap-3">
                                <Button
                                    type="submit"
                                    size="lg"
                                    disabled={processing}
                                >
                                    {processing && <Spinner />}
                                    <Sun />
                                    Send the report
                                </Button>
                                <p className="text-xs text-muted-foreground">
                                    You will get a report number straight away.
                                </p>
                            </div>
                        </>
                    )}
                </Form>

                <div className="mt-6 flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
                    <Info className="mt-0.5 size-3.5 shrink-0" />
                    <p>
                        We use these details to answer your report and arrange
                        service, warranty or network work.
                        {support.phone
                            ? ` If it is urgent and you would rather talk, call ${support.phone}.`
                            : ''}
                    </p>
                </div>
            </div>
        </>
    );
}
