import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { use{{ model.name }}Store } from '../../stores/use{{ model.name }}Store';
import { Button } from '../../components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '../../components/ui/card';
import { Badge } from '../../components/ui/badge';
import { Label } from '../../components/ui/label';
import { Separator } from '../../components/ui/separator';
import { FileUpload } from '../../components/ui/file-upload';
{% for fk in model.foreign_keys %}
import { get{{ fk.target_model }} } from '../../services/{{ fk.target_service }}';
{% endfor %}
{% if model.m2m_fields %}
{% for m2m in model.m2m_fields %}
import { get{{ model.name }}{{ m2m.target_model }}s } from '../../services/{{ model.module_name }}';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../components/ui/table';
{% endfor %}
{% endif %}

const {{ model.name }}DetailPage: React.FC = () => {
    const { t } = useTranslation();
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const { fetchItem, currentItem, loading } = use{{ model.name }}Store();
    
    // State to store resolved foreign key data
    {% for fk in model.foreign_keys %}
    const [{{ fk.target_service }}Data, set{{ fk.target_model }}Data] = useState<any>(null);
    {% endfor %}

    // State for M2M data
    {% if model.m2m_fields %}
    {% for m2m in model.m2m_fields %}
    const [{{ m2m.name }}Data, set{{ m2m.target_model }}Data] = useState<any[]>([]);
    const [{{ m2m.name }}Total, set{{ m2m.target_model }}Total] = useState(0);
    const [{{ m2m.name }}Page, set{{ m2m.target_model }}Page] = useState(1);
    const [{{ m2m.name }}Loading, set{{ m2m.target_model }}Loading] = useState(false);
    {% endfor %}
    {% endif %}

    useEffect(() => {
        if (id) {
            const itemId = parseInt(id);
            fetchItem(itemId).then((item) => {
                if (item) {
                    // Fetch FK data
                    {% for fk in model.foreign_keys %}
                    if (item.{{ fk.name.replace('_id', '') }}_id) {
                        get{{ fk.target_model }}(item.{{ fk.name.replace('_id', '') }}_id).then(set{{ fk.target_model }}Data);
                    }
                    {% endfor %}
                }
            });
            
            // Fetch M2M data
            {% if model.m2m_fields %}
            {% for m2m in model.m2m_fields %}
            fetch{{ m2m.target_model }}s(itemId, 1);
            {% endfor %}
            {% endif %}
        }
    }, [id, fetchItem]);

    {% if model.m2m_fields %}
    {% for m2m in model.m2m_fields %}
    const fetch{{ m2m.target_model }}s = async (itemId: number, page: number) => {
        set{{ m2m.target_model }}Loading(true);
        try {
            const result = await get{{ model.name }}{{ m2m.target_model }}s(itemId, page, 5); // Small page size for detail view
            set{{ m2m.target_model }}Data(result.items);
            set{{ m2m.target_model }}Total(result.total);
            set{{ m2m.target_model }}Page(result.page);
        } catch (error) {
            console.error(error);
        } finally {
            set{{ m2m.target_model }}Loading(false);
        }
    };
    {% endfor %}
    {% endif %}

    if (loading && !currentItem) {
        return (
            <div className="flex h-full items-center justify-center">
                <Loader2 className="h-8 w-8 animate-spin" />
            </div>
        );
    }

    if (!currentItem) {
        return (
            <div className="flex flex-col items-center justify-center space-y-4">
                <div className="text-xl font-semibold">Item not found</div>
                <Button onClick={() => navigate(-1)}>Go Back</Button>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <div className="flex items-center space-x-4">
                <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
                    <ArrowLeft className="h-4 w-4" />
                </Button>
                <h1 className="text-3xl font-bold tracking-tight">{{ model.name }} Details</h1>
            </div>

            <div className="grid gap-6 md:grid-cols-2">
                <Card>
                    <CardHeader>
                        <CardTitle>Basic Information</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        {% for field in model.fields %}
                        {% if not field.fk_info and 'r' in field.permissions %}
                        <div className="space-y-1">
                            <Label className="text-muted-foreground">{t('{{ field.label_key }}')}</Label>
                            <div className="font-medium">
                                {% if field.ui_type == 'bool' %}
                                <Badge variant={currentItem.{{ field.name }} ? "default" : "secondary"}>
                                    {currentItem.{{ field.name }} ? 'Yes' : 'No'}
                                </Badge>
                                {% elif field.is_enum %}
                                <Badge variant="outline">{currentItem.{{ field.name }}}</Badge>
                                {% elif field.ui_type == 'image' %}
                                {currentItem.{{ field.name }} ? (
                                    <div className="relative aspect-video w-full max-w-sm overflow-hidden rounded-lg border bg-muted">
                                        <img
                                            src={currentItem.{{ field.name }}}
                                            alt="{{ field.name }}"
                                            className="h-full w-full object-cover"
                                        />
                                    </div>
                                ) : (
                                    <span className="text-muted-foreground italic">No image</span>
                                )}
                                {% elif field.ui_type == 'file' %}
                                {currentItem.{{ field.name }} ? (
                                    <FileUpload 
                                        value={currentItem.{{ field.name }}} 
                                        onChange={() => {}} 
                                        readOnly={true}
                                        allowDownload={ {{ "true" if field.allow_download else "false" }} }
                                    />
                                ) : (
                                    <span className="text-muted-foreground italic">No file</span>
                                )}
                                {% else %}
                                {String(currentItem.{{ field.name }} ?? '-')}
                                {% endif %}
                            </div>
                        </div>
                        {% endif %}
                        {% endfor %}
                    </CardContent>
                </Card>

                {% if model.foreign_keys %}
                <Card>
                    <CardHeader>
                        <CardTitle>Related Information</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        {% for fk in model.foreign_keys %}
                        <div>
                            <div className="mb-2 flex items-center justify-between">
                                <Label className="text-lg font-semibold">{t('models.{{ fk.target_service }}.name')}</Label>
                                <Badge variant="outline">ID: {currentItem.{{ fk.name.replace('_id', '') }}_id}</Badge>
                            </div>
                            <div className="rounded-md border p-4">
                                { {{ fk.target_service }}Data ? (
                                    <div className="space-y-2">
                                        <div className="grid grid-cols-2 gap-2 text-sm">
                                            <span className="text-muted-foreground">Display Name:</span>
                                            <span className="font-medium">{ {{ fk.target_service }}Data.{{ fk.label_field }} }</span>
                                            
                                            {/* Show all readable fields for the target model */}
                                            {% if fk.target_readable_fields %}
                                            {% for target_field in fk.target_readable_fields %}
                                            {% if target_field.name != fk.label_field %}
                                            { {{ fk.target_service }}Data.{{ target_field.name }} !== undefined && (
                                                <>
                                                <span className="text-muted-foreground">{t('{{ target_field.label_key }}')}:</span>
                                                <span className="font-medium">
                                                    {% if target_field.ui_type == 'bool' %}
                                                    { {{ fk.target_service }}Data.{{ target_field.name }} ? 'Yes' : 'No' }
                                                    {% else %}
                                                    {String({{ fk.target_service }}Data.{{ target_field.name }} ?? '-')}
                                                    {% endif %}
                                                </span>
                                                </>
                                            )}
                                            {% endif %}
                                            {% endfor %}
                                            {% endif %}
                                        </div>
                                    </div>
                                ) : (
                                    <div className="flex items-center space-x-2 text-muted-foreground">
                                        <Loader2 className="h-4 w-4 animate-spin" />
                                        <span>Loading related data...</span>
                                    </div>
                                )}
                            </div>
                        </div>
                        {% if not loop.last %}<Separator />{% endif %}
                        {% endfor %}
                    </CardContent>
                </Card>
                {% endif %}

                {% if model.m2m_fields %}
                {% for m2m in model.m2m_fields %}
                <Card className="md:col-span-2">
                    <CardHeader>
                        <CardTitle>{t('models.{{ m2m.target_service }}.name')}s</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="rounded-md border">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>ID</TableHead>
                                        <TableHead>{{ m2m.label_field.title() }}</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    { {{ m2m.name }}Loading ? (
                                        <TableRow>
                                            <TableCell colSpan={2} className="h-24 text-center">
                                                <Loader2 className="mx-auto h-6 w-6 animate-spin" />
                                            </TableCell>
                                        </TableRow>
                                    ) : {{ m2m.name }}Data.length > 0 ? (
                                        {{ m2m.name }}Data.map((item) => (
                                            <TableRow key={item.id}>
                                                <TableCell>{item.id}</TableCell>
                                                <TableCell>{item.{{ m2m.label_field }} }</TableCell>
                                            </TableRow>
                                        ))
                                    ) : (
                                        <TableRow>
                                            <TableCell colSpan={2} className="h-24 text-center">
                                                No {{ m2m.target_model.lower() }}s found.
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                        <div className="mt-4 flex items-center justify-end space-x-2">
                             <Button
                                variant="outline"
                                size="sm"
                                onClick={() => fetch{{ m2m.target_model }}s(parseInt(id!), {{ m2m.name }}Page - 1)}
                                disabled={ {{ m2m.name }}Page <= 1 || {{ m2m.name }}Loading}
                            >
                                Previous
                            </Button>
                            <span className="text-sm">
                                Page { {{ m2m.name }}Page } of { Math.ceil({{ m2m.name }}Total / 5) || 1 }
                            </span>
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => fetch{{ m2m.target_model }}s(parseInt(id!), {{ m2m.name }}Page + 1)}
                                disabled={ {{ m2m.name }}Page >= Math.ceil({{ m2m.name }}Total / 5) || {{ m2m.name }}Loading}
                            >
                                Next
                            </Button>
                        </div>
                    </CardContent>
                </Card>
                {% endfor %}
                {% endif %}
            </div>
        </div>
    );
};

export default {{ model.name }}DetailPage;
