import React from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow
} from '@/components/ui/table';
import { ArrowLeft, Key, Monitor, Globe, Clock } from 'lucide-react';
import { __ } from '@/lib/i18n';

interface Activation {
    id: number;
    license_id: number;
    domain: string | null;
    ip_address: string | null;
    machine_id: string | null;
    user_agent: string | null;
    status: 'active' | 'deactivated';
    activated_at: string;
    deactivated_at: string | null;
}

interface LicenseDetail {
    id: number;
    license_key: string;
    product_id: number;
    product_name: string;
    order_id: number;
    user_id: number;
    user_email: string;
    user_name: string;
    status: 'active' | 'revoked' | 'expired';
    activation_limit: number;
    activation_count: number;
    activations_remaining: number;
    expires_at: string | null;
    is_expired: boolean;
    created_at: string;
    updated_at: string;
    activations: Activation[];
}

export default function LicenseDetail() {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();

    const { data: license, isLoading } = useQuery<LicenseDetail>({
        queryKey: ['license', id],
        queryFn: () => api.get(`/licenses/${id}`),
        enabled: !!id,
    });

    if (isLoading) {
        return (
            <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
        );
    }

    if (!license) {
        return (
            <div className="text-center py-12">
                <p className="text-muted-foreground">{__('License not found')}</p>
                <Button variant="link" onClick={() => navigate('/products/licenses')}>
                    {__('Back to Licenses')}
                </Button>
            </div>
        );
    }

    const getStatusBadge = () => {
        if (license.status === 'revoked') {
            return <Badge variant="destructive">{__('Revoked')}</Badge>;
        }
        if (license.is_expired) {
            return <Badge variant="secondary">{__('Expired')}</Badge>;
        }
        return <Badge variant="default">{__('Active')}</Badge>;
    };

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center gap-4">
                <Button variant="ghost" size="icon" onClick={() => navigate('/products/licenses')}>
                    <ArrowLeft className="h-4 w-4" />
                </Button>
                <div>
                    <h1 className="text-2xl font-bold flex items-center gap-2">
                        <Key className="h-6 w-6" />
                        {__('License Details')}
                    </h1>
                    <p className="text-muted-foreground font-mono text-sm">{license.license_key}</p>
                </div>
                <div className="ml-auto">{getStatusBadge()}</div>
            </div>

            {/* Info Cards */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium">{__('Product')}</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <p className="font-semibold">{license.product_name}</p>
                        <p className="text-xs text-muted-foreground">Order #{license.order_id}</p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium">{__('Customer')}</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <p className="font-semibold">{license.user_name}</p>
                        <p className="text-xs text-muted-foreground">{license.user_email}</p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium">{__('Activations')}</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <p className="font-semibold">
                            {license.activation_count} / {license.activation_limit === 0 ? '∞' : license.activation_limit}
                        </p>
                        <p className="text-xs text-muted-foreground">
                            {license.activations_remaining === -1 ? __('Unlimited') : `${license.activations_remaining} ${__('remaining')}`}
                        </p>
                    </CardContent>
                </Card>
            </div>

            {/* Dates */}
            <Card>
                <CardHeader>
                    <CardTitle className="text-sm font-medium">{__('Dates')}</CardTitle>
                </CardHeader>
                <CardContent>
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                        <div>
                            <p className="text-muted-foreground">{__('Created')}</p>
                            <p>{new Date(license.created_at).toLocaleString()}</p>
                        </div>
                        <div>
                            <p className="text-muted-foreground">{__('Expires')}</p>
                            <p className={license.is_expired ? 'text-red-500' : ''}>
                                {license.expires_at ? new Date(license.expires_at).toLocaleDateString() : __('Never')}
                            </p>
                        </div>
                    </div>
                </CardContent>
            </Card>

            {/* Activations */}
            <Card>
                <CardHeader>
                    <CardTitle>{__('Activation History')}</CardTitle>
                    <CardDescription>
                        {__('All activations and deactivations for this license')}
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    {license.activations.length === 0 ? (
                        <p className="text-center py-8 text-muted-foreground">
                            {__('No activations yet')}
                        </p>
                    ) : (
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>{__('Domain/Machine')}</TableHead>
                                    <TableHead>{__('IP Address')}</TableHead>
                                    <TableHead>{__('Activated')}</TableHead>
                                    <TableHead>{__('Status')}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {license.activations.map((activation) => (
                                    <TableRow key={activation.id}>
                                        <TableCell>
                                            <div className="flex items-center gap-2">
                                                {activation.domain ? (
                                                    <>
                                                        <Globe className="h-4 w-4 text-muted-foreground" />
                                                        <span>{activation.domain}</span>
                                                    </>
                                                ) : activation.machine_id ? (
                                                    <>
                                                        <Monitor className="h-4 w-4 text-muted-foreground" />
                                                        <span className="font-mono text-xs">{activation.machine_id}</span>
                                                    </>
                                                ) : (
                                                    <span className="text-muted-foreground">{__('Unknown')}</span>
                                                )}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <span className="font-mono text-xs">{activation.ip_address || '-'}</span>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex items-center gap-1">
                                                <Clock className="h-3 w-3 text-muted-foreground" />
                                                {new Date(activation.activated_at).toLocaleString()}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            {activation.status === 'active' ? (
                                                <Badge variant="default">{__('Active')}</Badge>
                                            ) : (
                                                <Badge variant="secondary">{__('Deactivated')}</Badge>
                                            )}
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    )}
                </CardContent>
            </Card>
        </div>
    );
}
