import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
import {
    ArrowLeft,
    Clock,
    MapPin,
    Monitor,
    Send,
    User2,
    Eye,
    EyeOff,
    Calendar,
} from 'lucide-react';
import { useState } from 'react';
import { TicketPriorityBadge } from '@/components/ticket-priority-badge';
import { TicketStatusBadge } from '@/components/ticket-status-badge';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem, PriorityMap, StatusMap, Ticket, User } from '@/types';

const categoryLabels: Record<string, string> = {
    hardware_repair: 'Hardware Repair',
    software_issue: 'Software Issue',
    network: 'Network',
    printer: 'Printer',
    account_access: 'Account Access',
    other: 'Other',
};

type Props = {
    ticket: Ticket;
    technicians: { id: number; name: string }[];
    statuses: StatusMap;
    priorities: PriorityMap;
    canManage: boolean;
};

export default function TicketShow({ ticket, technicians, statuses, priorities, canManage }: Props) {
    const { auth } = usePage<{ auth: { user: User } }>().props;
    const [showInternalInput, setShowInternalInput] = useState(false);

    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Dashboard', href: '/dashboard' },
        { title: 'Tickets', href: '/tickets' },
        { title: ticket.ticket_number, href: `/tickets/${ticket.id}` },
    ];

    // Comment form
    const commentForm = useForm({
        body: '',
        is_internal: false,
    });

    // Management form
    const manageForm = useForm({
        status: ticket.status,
        priority: ticket.priority,
        assigned_to: ticket.assignee?.id?.toString() || '',
    });

    function submitComment(e: React.FormEvent) {
        e.preventDefault();
        commentForm.post(`/tickets/${ticket.id}/comments`, {
            preserveScroll: true,
            onSuccess: () => {
                commentForm.reset();
                setShowInternalInput(false);
            },
        });
    }

    function updateTicket(field: string, value: string) {
        manageForm.setData(field as any, value);
        const updateData: Record<string, string> = { [field]: value };
        if (field === 'assigned_to' && value && ticket.status === 'open') {
            updateData.status = 'in_progress';
            manageForm.setData('status', 'in_progress');
        }
        router.put(`/tickets/${ticket.id}`, updateData, {
            preserveScroll: true,
        });
    }

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`${ticket.ticket_number} - ${ticket.title}`} />
            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                {/* Header */}
                <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                    <div className="flex items-start gap-3">
                        <Link href="/tickets">
                            <Button variant="ghost" size="icon" className="mt-0.5 shrink-0">
                                <ArrowLeft className="h-4 w-4" />
                            </Button>
                        </Link>
                        <div>
                            <div className="flex items-center gap-2 mb-1">
                                <span className="text-sm font-mono text-muted-foreground">
                                    {ticket.ticket_number}
                                </span>
                                <TicketStatusBadge status={ticket.status} />
                                <TicketPriorityBadge priority={ticket.priority} />
                            </div>
                            <h1 className="text-xl font-bold tracking-tight">{ticket.title}</h1>
                        </div>
                    </div>
                    <div className="flex items-center gap-2">
                        {(canManage || ticket.requester?.id === auth.user.id) && (
                            <Link href={`/tickets/${ticket.id}/edit`}>
                                <Button variant="outline" size="sm">
                                    Edit Ticket
                                </Button>
                            </Link>
                        )}
                        {!canManage && ticket.requester?.id === auth.user.id && ticket.status !== 'closed' && ticket.status !== 'resolved' && (
                            <Button
                                variant="default"
                                size="sm"
                                className="bg-emerald-600 hover:bg-emerald-700"
                                onClick={() => updateTicket('status', 'resolved')}
                            >
                                Mark as Resolved
                            </Button>
                        )}
                    </div>
                </div>

                <div className="grid gap-6 lg:grid-cols-3">
                    {/* Main Content */}
                    <div className="space-y-6 lg:col-span-2">
                        {/* Description */}
                        <Card>
                            <CardHeader className="pb-3">
                                <CardTitle className="text-base">Description</CardTitle>
                            </CardHeader>
                            <CardContent>
                                <div className="prose prose-sm max-w-none text-sm whitespace-pre-wrap text-foreground/80">
                                    {ticket.description}
                                </div>
                            </CardContent>
                        </Card>

                        {/* Comments */}
                        <Card>
                            <CardHeader className="pb-3">
                                <CardTitle className="text-base">
                                    Activity ({ticket.comments?.length || 0})
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                {ticket.comments && ticket.comments.length > 0 ? (
                                    ticket.comments.map((comment) => (
                                        <div
                                            key={comment.id}
                                            className={`rounded-lg border p-4 ${comment.is_internal
                                                ? 'border-amber-200 bg-amber-50/50 dark:border-amber-900 dark:bg-amber-950/20'
                                                : ''
                                                }`}
                                        >
                                            <div className="flex items-center gap-2 mb-2">
                                                <div className="flex h-7 w-7 items-center justify-center rounded-full bg-primary/10 text-xs font-bold text-primary">
                                                    {comment.user.name[0]}
                                                </div>
                                                <div>
                                                    <span className="text-sm font-medium">
                                                        {comment.user.name}
                                                    </span>
                                                    {comment.user.role && comment.user.role !== 'user' && (
                                                        <Badge variant="outline" className="ml-1 text-[10px] px-1.5 py-0">
                                                            {comment.user.role}
                                                        </Badge>
                                                    )}
                                                </div>
                                                <span className="text-xs text-muted-foreground ml-auto">
                                                    {new Date(comment.created_at).toLocaleString()}
                                                </span>
                                                {comment.is_internal && (
                                                    <Badge
                                                        variant="outline"
                                                        className="text-[10px] border-amber-300 text-amber-700 dark:text-amber-400"
                                                    >
                                                        <EyeOff className="h-3 w-3 mr-1" />
                                                        Internal
                                                    </Badge>
                                                )}
                                            </div>
                                            <p className="text-sm pl-9 whitespace-pre-wrap text-foreground/80">
                                                {comment.body}
                                            </p>
                                        </div>
                                    ))
                                ) : (
                                    <p className="text-sm text-muted-foreground text-center py-6">
                                        No comments yet. Be the first to comment.
                                    </p>
                                )}

                                <Separator />

                                {/* Add Comment */}
                                <form onSubmit={submitComment} className="space-y-3">
                                    <Textarea
                                        value={commentForm.data.body}
                                        onChange={(e) => commentForm.setData('body', e.target.value)}
                                        placeholder="Write a comment..."
                                        rows={3}
                                        className="text-sm"
                                    />
                                    <div className="flex items-center justify-between">
                                        <div>
                                            {canManage && (
                                                <Button
                                                    type="button"
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() => {
                                                        setShowInternalInput(!showInternalInput);
                                                        commentForm.setData('is_internal', !commentForm.data.is_internal);
                                                    }}
                                                    className={`text-xs gap-1 ${commentForm.data.is_internal
                                                        ? 'text-amber-600'
                                                        : ''
                                                        }`}
                                                >
                                                    {commentForm.data.is_internal ? (
                                                        <>
                                                            <EyeOff className="h-3 w-3" />
                                                            Internal Note
                                                        </>
                                                    ) : (
                                                        <>
                                                            <Eye className="h-3 w-3" />
                                                            Public Comment
                                                        </>
                                                    )}
                                                </Button>
                                            )}
                                        </div>
                                        <Button
                                            type="submit"
                                            size="sm"
                                            disabled={commentForm.processing || !commentForm.data.body.trim()}
                                            className="gap-1"
                                        >
                                            <Send className="h-3 w-3" />
                                            Send
                                        </Button>
                                    </div>
                                </form>
                            </CardContent>
                        </Card>
                    </div>

                    {/* Sidebar Info */}
                    <div className="space-y-6">
                        {/* Ticket Info */}
                        <Card>
                            <CardHeader className="pb-3">
                                <CardTitle className="text-base">Details</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                <div className="space-y-3 text-sm">
                                    <div className="flex items-center gap-3">
                                        <User2 className="h-4 w-4 text-muted-foreground shrink-0" />
                                        <div>
                                            <p className="text-xs text-muted-foreground">Requester</p>
                                            <p className="font-medium">{ticket.requester?.name}</p>
                                            {ticket.requester?.department && (
                                                <p className="text-xs text-muted-foreground">
                                                    {ticket.requester.department}
                                                </p>
                                            )}
                                        </div>
                                    </div>

                                    <Separator />

                                    <div className="flex items-center gap-3">
                                        <Monitor className="h-4 w-4 text-muted-foreground shrink-0" />
                                        <div>
                                            <p className="text-xs text-muted-foreground">Category</p>
                                            <p className="font-medium">
                                                {categoryLabels[ticket.category] || ticket.category}
                                            </p>
                                        </div>
                                    </div>

                                    {ticket.location && (
                                        <>
                                            <Separator />
                                            <div className="flex items-center gap-3">
                                                <MapPin className="h-4 w-4 text-muted-foreground shrink-0" />
                                                <div>
                                                    <p className="text-xs text-muted-foreground">Location</p>
                                                    <p className="font-medium">{ticket.location}</p>
                                                </div>
                                            </div>
                                        </>
                                    )}

                                    {ticket.equipment_type && (
                                        <>
                                            <Separator />
                                            <div className="flex items-center gap-3">
                                                <Monitor className="h-4 w-4 text-muted-foreground shrink-0" />
                                                <div>
                                                    <p className="text-xs text-muted-foreground">Equipment</p>
                                                    <p className="font-medium">{ticket.equipment_type}</p>
                                                </div>
                                            </div>
                                        </>
                                    )}

                                    <Separator />

                                    <div className="flex items-center gap-3">
                                        <Calendar className="h-4 w-4 text-muted-foreground shrink-0" />
                                        <div>
                                            <p className="text-xs text-muted-foreground">Created</p>
                                            <p className="font-medium">
                                                {new Date(ticket.created_at).toLocaleString()}
                                            </p>
                                        </div>
                                    </div>

                                    {ticket.resolved_at && (
                                        <>
                                            <Separator />
                                            <div className="flex items-center gap-3">
                                                <Clock className="h-4 w-4 text-muted-foreground shrink-0" />
                                                <div>
                                                    <p className="text-xs text-muted-foreground">Resolved</p>
                                                    <p className="font-medium">
                                                        {new Date(ticket.resolved_at).toLocaleString()}
                                                    </p>
                                                </div>
                                            </div>
                                        </>
                                    )}
                                </div>
                            </CardContent>
                        </Card>

                        {/* Management Panel - Staff Only */}
                        {canManage && (
                            <Card className="border-primary/30">
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-base">Manage Ticket</CardTitle>
                                    <CardDescription>Staff controls</CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    <div className="space-y-2">
                                        <label className="text-xs font-medium text-muted-foreground">
                                            Status
                                        </label>
                                        <Select
                                            value={manageForm.data.status}
                                            onValueChange={(v) => updateTicket('status', v)}
                                        >
                                            <SelectTrigger>
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {Object.entries(statuses).map(([key, label]) => (
                                                    <SelectItem key={key} value={key}>
                                                        {label}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="text-xs font-medium text-muted-foreground">
                                            Priority
                                        </label>
                                        <Select
                                            value={manageForm.data.priority}
                                            onValueChange={(v) => updateTicket('priority', v)}
                                        >
                                            <SelectTrigger>
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {Object.entries(priorities).map(([key, label]) => (
                                                    <SelectItem key={key} value={key}>
                                                        {label}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="text-xs font-medium text-muted-foreground">
                                            Assign To
                                        </label>
                                        <Select
                                            value={manageForm.data.assigned_to}
                                            onValueChange={(v) => updateTicket('assigned_to', v)}
                                        >
                                            <SelectTrigger>
                                                <SelectValue placeholder="Unassigned" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {technicians.map((tech) => (
                                                    <SelectItem key={tech.id} value={tech.id.toString()}>
                                                        {tech.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </CardContent>
                            </Card>
                        )}
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}
