import { Head, useForm } from '@inertiajs/react';
import {
    Wrench,
    Monitor,
    Wifi,
    Printer,
    KeyRound,
    HelpCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import InputError from '@/components/input-error';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem, CategoryMap, PriorityMap } from '@/types';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Tickets', href: '/tickets' },
    { title: 'New Ticket', href: '/tickets/create' },
];

const categoryIcons: Record<string, React.ReactNode> = {
    hardware_repair: <Wrench className="h-5 w-5" />,
    software_issue: <Monitor className="h-5 w-5" />,
    network: <Wifi className="h-5 w-5" />,
    printer: <Printer className="h-5 w-5" />,
    account_access: <KeyRound className="h-5 w-5" />,
    other: <HelpCircle className="h-5 w-5" />,
};

type Props = {
    categories: CategoryMap;
    priorities: PriorityMap;
};

export default function TicketCreate({ categories, priorities }: Props) {
    const { data, setData, post, processing, errors } = useForm({
        title: '',
        description: '',
        category: '',
        priority: 'medium',
        location: '',
        equipment_type: '',
    });

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        post('/tickets');
    }

    const showEquipment = ['hardware_repair', 'printer'].includes(data.category);

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="New Ticket" />
            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">Submit a New Ticket</h1>
                    <p className="text-sm text-muted-foreground">
                        Describe your ICT issue and we'll get it resolved as soon as possible.
                    </p>
                </div>

                <form onSubmit={handleSubmit} className="space-y-6">
                    {/* Category Selection */}
                    <Card>
                        <CardHeader className="pb-3">
                            <CardTitle className="text-base">What type of issue?</CardTitle>
                            <CardDescription>Select the category that best describes your problem</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
                                {Object.entries(categories).map(([key, label]) => (
                                    <button
                                        key={key}
                                        type="button"
                                        onClick={() => setData('category', key)}
                                        className={`flex flex-col items-center gap-2 rounded-xl border-2 p-4 transition-all duration-200 hover:shadow-md ${data.category === key
                                                ? 'border-primary bg-primary/5 shadow-md'
                                                : 'border-border hover:border-primary/50'
                                            }`}
                                    >
                                        <div
                                            className={`rounded-lg p-2 transition-colors ${data.category === key
                                                    ? 'bg-primary text-primary-foreground'
                                                    : 'bg-muted text-muted-foreground'
                                                }`}
                                        >
                                            {categoryIcons[key]}
                                        </div>
                                        <span className="text-xs font-medium text-center">{label}</span>
                                    </button>
                                ))}
                            </div>
                            <InputError message={errors.category} className="mt-2" />
                        </CardContent>
                    </Card>

                    {/* Ticket Details */}
                    <Card>
                        <CardHeader className="pb-3">
                            <CardTitle className="text-base">Ticket Details</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="title">Subject *</Label>
                                <Input
                                    id="title"
                                    value={data.title}
                                    onChange={(e) => setData('title', e.target.value)}
                                    placeholder="Brief summary of your issue"
                                    className="text-sm"
                                />
                                <InputError message={errors.title} />
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="description">Description *</Label>
                                <Textarea
                                    id="description"
                                    value={data.description}
                                    onChange={(e) => setData('description', e.target.value)}
                                    placeholder="Please describe the issue in detail. Include any error messages, when the problem started, and what you've already tried."
                                    rows={5}
                                    className="text-sm"
                                />
                                <InputError message={errors.description} />
                            </div>

                            <div className="grid gap-4 sm:grid-cols-2">
                                <div className="space-y-2">
                                    <Label htmlFor="priority">Priority *</Label>
                                    <Select
                                        value={data.priority}
                                        onValueChange={(v) => setData('priority', v)}
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Select priority" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {Object.entries(priorities).map(([key, label]) => (
                                                <SelectItem key={key} value={key}>
                                                    {label}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    <InputError message={errors.priority} />
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="location">Location</Label>
                                    <Input
                                        id="location"
                                        value={data.location}
                                        onChange={(e) => setData('location', e.target.value)}
                                        placeholder="e.g., Room 201, Admin Building"
                                        className="text-sm"
                                    />
                                    <InputError message={errors.location} />
                                </div>
                            </div>

                            {showEquipment && (
                                <div className="space-y-2">
                                    <Label htmlFor="equipment_type">Equipment Type</Label>
                                    <Input
                                        id="equipment_type"
                                        value={data.equipment_type}
                                        onChange={(e) => setData('equipment_type', e.target.value)}
                                        placeholder="e.g., Dell OptiPlex 7090, Canon imageRUNNER 2530"
                                        className="text-sm"
                                    />
                                    <InputError message={errors.equipment_type} />
                                </div>
                            )}
                        </CardContent>
                    </Card>

                    <div className="flex justify-end gap-3">
                        <Button type="button" variant="outline" onClick={() => window.history.back()}>
                            Cancel
                        </Button>
                        <Button type="submit" disabled={processing} className="min-w-[120px]">
                            {processing ? 'Submitting...' : 'Submit Ticket'}
                        </Button>
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}
