import { Head, router, useForm } from '@inertiajs/react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import type { Ticket, User } from '@/types';
import { useState } from 'react';

const statusColors: Record<string, string> = {
    open: 'bg-blue-100 text-blue-800',
    in_progress: 'bg-yellow-100 text-yellow-800',
    pending: 'bg-orange-100 text-orange-800',
    resolved: 'bg-green-100 text-green-800',
    closed: 'bg-gray-100 text-gray-800',
};

const priorityColors: Record<string, string> = {
    low: 'bg-slate-100 text-slate-800',
    medium: 'bg-blue-100 text-blue-800',
    high: 'bg-orange-100 text-orange-800',
    critical: 'bg-red-100 text-red-800',
};

type Props = {
    ticket: Ticket;
    agents: Pick<User, 'id' | 'name'>[];
};

export default function ShowTicket({ ticket, agents }: Props) {
    const commentForm = useForm({ body: '', is_internal: false });
    const [assignTo, setAssignTo] = useState(String(ticket.assigned_to ?? ''));

    function handleComment(e: React.FormEvent) {
        e.preventDefault();
        commentForm.post(`/tickets/${ticket.id}/comments`, {
            preserveScroll: true,
            onSuccess: () => commentForm.reset(),
        });
    }

    function handleAssign() {
        if (assignTo) {
            router.put(
                `/tickets/${ticket.id}/assign`,
                { assigned_to: Number(assignTo) },
                { preserveScroll: true },
            );
        }
    }

    function handleStatusChange(status: string) {
        router.put(
            `/tickets/${ticket.id}`,
            { status },
            { preserveScroll: true },
        );
    }

    return (
        <>
            <Head title={`Ticket ${ticket.ticket_no}`} />
            <div className="mx-auto max-w-5xl space-y-6 p-4">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="flex items-center gap-3 text-2xl font-bold">
                            {ticket.ticket_no}
                            <span
                                className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${priorityColors[ticket.priority]}`}
                            >
                                {ticket.priority}
                            </span>
                            <span
                                className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${statusColors[ticket.status]}`}
                            >
                                {ticket.status.replace('_', ' ')}
                            </span>
                        </h1>
                        <p className="mt-1 text-lg">{ticket.title}</p>
                    </div>
                    <Button
                        variant="outline"
                        onClick={() => router.visit('/tickets')}
                    >
                        Back to Tickets
                    </Button>
                </div>

                <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                    {/* Main content */}
                    <div className="space-y-6 lg:col-span-2">
                        {/* Description */}
                        <Card>
                            <CardHeader>
                                <CardTitle>Description</CardTitle>
                            </CardHeader>
                            <CardContent>
                                <p className="whitespace-pre-wrap">
                                    {ticket.description}
                                </p>
                                {ticket.metadata &&
                                    Object.keys(ticket.metadata).length > 0 && (
                                        <div className="mt-4 space-y-1 border-t pt-4">
                                            <h4 className="text-sm font-medium">
                                                Additional Details
                                            </h4>
                                            {Object.entries(
                                                ticket.metadata,
                                            ).map(([key, value]) => (
                                                <p
                                                    key={key}
                                                    className="text-sm"
                                                >
                                                    <span className="font-medium">
                                                        {key.replace('_', ' ')}:
                                                    </span>{' '}
                                                    {String(value)}
                                                </p>
                                            ))}
                                        </div>
                                    )}
                            </CardContent>
                        </Card>

                        {/* Attachments */}
                        {(ticket.attachments?.length ?? 0) > 0 && (
                            <Card>
                                <CardHeader>
                                    <CardTitle>Attachments</CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <ul className="space-y-2">
                                        {ticket.attachments!.map((att) => (
                                            <li
                                                key={att.id}
                                                className="flex items-center gap-2 text-sm"
                                            >
                                                <span>{att.file_name}</span>
                                                <span className="text-muted-foreground">
                                                    (
                                                    {(
                                                        att.file_size / 1024
                                                    ).toFixed(1)}{' '}
                                                    KB)
                                                </span>
                                            </li>
                                        ))}
                                    </ul>
                                </CardContent>
                            </Card>
                        )}

                        {/* Comments */}
                        <Card>
                            <CardHeader>
                                <CardTitle>Comments</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                {ticket.comments?.map((comment) => (
                                    <div
                                        key={comment.id}
                                        className={`rounded-md border p-3 ${comment.is_internal ? 'border-yellow-200 bg-yellow-50 dark:border-yellow-800 dark:bg-yellow-950' : ''}`}
                                    >
                                        <div className="flex items-center justify-between text-sm">
                                            <span className="font-medium">
                                                {comment.user?.name}
                                            </span>
                                            <span className="text-muted-foreground">
                                                {new Date(
                                                    comment.created_at,
                                                ).toLocaleString()}
                                            </span>
                                        </div>
                                        {comment.is_internal && (
                                            <Badge
                                                variant="outline"
                                                className="mt-1 text-xs"
                                            >
                                                Internal Note
                                            </Badge>
                                        )}
                                        <p className="mt-2 text-sm whitespace-pre-wrap">
                                            {comment.body}
                                        </p>
                                    </div>
                                ))}
                                {(!ticket.comments ||
                                    ticket.comments.length === 0) && (
                                    <p className="text-sm text-muted-foreground">
                                        No comments yet.
                                    </p>
                                )}

                                <Separator />

                                <form
                                    onSubmit={handleComment}
                                    className="space-y-3"
                                >
                                    <textarea
                                        value={commentForm.data.body}
                                        onChange={(e) =>
                                            commentForm.setData(
                                                'body',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Add a comment..."
                                        rows={3}
                                        className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
                                    />
                                    <div className="flex items-center gap-3">
                                        <label className="flex items-center gap-2 text-sm">
                                            <input
                                                type="checkbox"
                                                checked={
                                                    commentForm.data.is_internal
                                                }
                                                onChange={(e) =>
                                                    commentForm.setData(
                                                        'is_internal',
                                                        e.target.checked,
                                                    )
                                                }
                                                className="rounded border-gray-300"
                                            />
                                            Internal note
                                        </label>
                                        <Button
                                            type="submit"
                                            size="sm"
                                            disabled={
                                                commentForm.processing ||
                                                !commentForm.data.body
                                            }
                                        >
                                            Add Comment
                                        </Button>
                                    </div>
                                </form>
                            </CardContent>
                        </Card>

                        {/* Activity Log */}
                        {(ticket.activities?.length ?? 0) > 0 && (
                            <Card>
                                <CardHeader>
                                    <CardTitle>Activity Log</CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <ul className="space-y-2">
                                        {ticket.activities!.map((activity) => (
                                            <li
                                                key={activity.id}
                                                className="flex items-center justify-between border-b pb-2 text-sm last:border-0"
                                            >
                                                <span>
                                                    {activity.description}
                                                </span>
                                                <span className="text-xs text-muted-foreground">
                                                    {new Date(
                                                        activity.created_at,
                                                    ).toLocaleString()}
                                                </span>
                                            </li>
                                        ))}
                                    </ul>
                                </CardContent>
                            </Card>
                        )}
                    </div>

                    {/* Sidebar */}
                    <div className="space-y-4">
                        <Card>
                            <CardHeader>
                                <CardTitle>Details</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3 text-sm">
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Company
                                    </span>
                                    <span className="font-medium">
                                        {ticket.company?.name}
                                    </span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        System
                                    </span>
                                    <span className="font-medium">
                                        {ticket.system?.name}
                                    </span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Category
                                    </span>
                                    <span className="font-medium">
                                        {ticket.category?.name}
                                    </span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Source
                                    </span>
                                    <span className="font-medium">
                                        {ticket.source}
                                    </span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Created By
                                    </span>
                                    <span className="font-medium">
                                        {ticket.creator?.name}
                                    </span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">
                                        Created
                                    </span>
                                    <span className="font-medium">
                                        {new Date(
                                            ticket.created_at,
                                        ).toLocaleDateString()}
                                    </span>
                                </div>
                                {ticket.due_at && (
                                    <div className="flex justify-between">
                                        <span className="text-muted-foreground">
                                            SLA Due
                                        </span>
                                        <span
                                            className={`font-medium ${new Date(ticket.due_at) < new Date() ? 'text-red-600' : ''}`}
                                        >
                                            {new Date(
                                                ticket.due_at,
                                            ).toLocaleString()}
                                        </span>
                                    </div>
                                )}
                                {ticket.resolved_at && (
                                    <div className="flex justify-between">
                                        <span className="text-muted-foreground">
                                            Resolved
                                        </span>
                                        <span className="font-medium">
                                            {new Date(
                                                ticket.resolved_at,
                                            ).toLocaleString()}
                                        </span>
                                    </div>
                                )}
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Assignment</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                <Select
                                    value={assignTo}
                                    onValueChange={setAssignTo}
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select agent" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {agents.map((a) => (
                                            <SelectItem
                                                key={a.id}
                                                value={String(a.id)}
                                            >
                                                {a.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <Button
                                    size="sm"
                                    className="w-full"
                                    onClick={handleAssign}
                                    disabled={!assignTo}
                                >
                                    Assign
                                </Button>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Change Status</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-2">
                                {[
                                    'open',
                                    'in_progress',
                                    'pending',
                                    'resolved',
                                    'closed',
                                ].map((s) => (
                                    <Button
                                        key={s}
                                        variant={
                                            ticket.status === s
                                                ? 'default'
                                                : 'outline'
                                        }
                                        size="sm"
                                        className="w-full"
                                        onClick={() => handleStatusChange(s)}
                                        disabled={ticket.status === s}
                                    >
                                        {s.replace('_', ' ')}
                                    </Button>
                                ))}
                            </CardContent>
                        </Card>

                        {/* File Upload */}
                        <Card>
                            <CardHeader>
                                <CardTitle>Upload Attachment</CardTitle>
                            </CardHeader>
                            <CardContent>
                                <form
                                    onSubmit={(e) => {
                                        e.preventDefault();
                                        const formData = new FormData(
                                            e.currentTarget,
                                        );
                                        router.post(
                                            `/tickets/${ticket.id}/attachments`,
                                            Object.fromEntries(formData) as any,
                                            { preserveScroll: true },
                                        );
                                    }}
                                >
                                    <input
                                        type="file"
                                        name="file"
                                        className="mb-2 w-full text-sm"
                                    />
                                    <Button
                                        type="submit"
                                        size="sm"
                                        className="w-full"
                                    >
                                        Upload
                                    </Button>
                                </form>
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </>
    );
}
