import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@admin/components/ui/card';
import { Input } from '@admin/components/ui/input';
import { Label } from '@admin/components/ui/label';
import AppLayout from '@admin/layouts/app-layout';
import SettingsLayout from '@admin/layouts/settings/layout';
import { Head, router, usePage } from '@inertiajs/react';
import { ArrowLeft, Edit2, Plus, Save, Search, Trash2 } from 'lucide-react';
import { ReactNode, useState } from 'react';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@admin/components/ui/alert-dialog';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@admin/components/ui/dialog';
import { Textarea } from '@admin/components/ui/textarea';
import { Badge } from '@admin/components/ui/badge';
import { ScrollArea } from '@admin/components/ui/scroll-area';

// Project globals (Ziggy / Inertia route helper)
declare const route: (...args: any[]) => string;

interface Translation {
    key: string;
    value: string;
}

interface LanguageData {
    id: number;
    name: string;
    code: string;
    icon: string | null;
}

interface TranslateProps {
    language: LanguageData;
    langId: number;
    translations: Translation[];
}

export default function Translate({ language, langId, translations }: TranslateProps) {
    const [searchTerm, setSearchTerm] = useState('');
    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [newKey, setNewKey] = useState('');
    const [newValue, setNewValue] = useState('');
    const [editKey, setEditKey] = useState('');
    const [editValue, setEditValue] = useState('');
    const [editingKey, setEditingKey] = useState<string | null>(null);
    const [editingValue, setEditingValue] = useState('');

    const filteredTranslations = translations.filter(
        (t) =>
            t.key.toLowerCase().includes(searchTerm.toLowerCase()) ||
            t.value.toLowerCase().includes(searchTerm.toLowerCase())
    );

    // Group translations alphabetically by first letter of key
    const groupedTranslations = filteredTranslations.reduce((groups, translation) => {
        const firstLetter = translation.key.charAt(0).toUpperCase();
        if (!groups[firstLetter]) {
            groups[firstLetter] = [];
        }
        groups[firstLetter].push(translation);
        return groups;
    }, {} as Record<string, Translation[]>);

    // Sort groups alphabetically
    const sortedGroups = Object.keys(groupedTranslations).sort();

    const handleAddTranslation = () => {
        if (!newKey.trim() || !newValue.trim()) {
            alert('Both key and value are required');
            return;
        }

        router.post(route('language.store.key', langId), {
            key: newKey.trim(),
            value: newValue.trim(),
        }, {
            onSuccess: () => {
                setNewKey('');
                setNewValue('');
                setIsAddModalOpen(false);
            }
        });
    };

    const handleEditTranslation = () => {
        if (!editKey.trim() || !editValue.trim()) {
            alert('Both key and value are required');
            return;
        }

        router.put(route('language.update.key', langId), {
            key: editKey.trim(),
            value: editValue.trim(),
        }, {
            onSuccess: () => {
                setEditKey('');
                setEditValue('');
                setIsEditModalOpen(false);
            }
        });
    };

    const handleDeleteTranslation = (key: string) => {
        router.delete(route('language.delete.key', langId), {
            data: { key },
        });
    };

    const openEditModal = (translation: Translation) => {
        setEditKey(translation.key);
        setEditValue(translation.value);
        setIsEditModalOpen(true);
    };

    const startInlineEdit = (translation: Translation) => {
        setEditingKey(translation.key);
        setEditingValue(translation.value);
    };

    const saveInlineEdit = (key: string) => {
        if (!editingValue.trim()) {
            alert('Translation value is required');
            return;
        }

        router.put(route('language.update.key', langId), {
            key: key,
            value: editingValue.trim(),
        }, {
            onSuccess: () => {
                setEditingKey(null);
                setEditingValue('');
            }
        });
    };

    const cancelInlineEdit = () => {
        setEditingKey(null);
        setEditingValue('');
    };

    return (
        <>
            <Head title={`Translate: ${language.name}`} />
            <SettingsLayout tab="platform">
            <div className="flex h-full flex-1 flex-col gap-4 overflow-x-auto rounded-xl p-2">
                {/* Header Section */}
                <div className="flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center">
                    <div className="grid grid-cols-1 gap-1">
                        <h2 className="text-xl font-bold sm:text-2xl">
                            {language.name} Translations
                        </h2>
                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                            <Badge variant="outline" className="font-mono text-xs">
                                {language.code.toUpperCase()}
                            </Badge>
                            <span>•</span>
                            <span>{translations.length} keys</span>
                        </div>
                    </div>
                    <div className="flex flex-wrap gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => router.visit(route('language.index'))}
                        >
                            <ArrowLeft className="mr-2 h-4 w-4" />
                            Back to List
                        </Button>
                        <Button
                            onClick={() => setIsAddModalOpen(true)}
                            size="sm"
                        >
                            <Plus className="h-4 w-4 mr-2" />
                            Add Key
                        </Button>
                    </div>
                </div>

                {/* Search */}
                <Card>
                    <CardContent className="p-3">
                        <div className="relative">
                            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input
                                type="text"
                                placeholder="Search by key or value..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="pl-10 h-9"
                            />
                        </div>
                    </CardContent>
                </Card>

                {/* Translations List */}
                <Card className="flex-1">
                    <CardContent className="p-0">
                        <ScrollArea className="h-[calc(100vh-240px)]">
                            {filteredTranslations.length === 0 ? (
                                <div className="flex flex-col items-center justify-center py-16 text-center">
                                    <Search className="h-10 w-10 text-muted-foreground/50 mb-3" />
                                    <h3 className="text-base font-medium mb-1">
                                        {searchTerm ? 'No matches found' : 'No translations yet'}
                                    </h3>
                                    <p className="text-sm text-muted-foreground max-w-sm mb-4">
                                        {searchTerm
                                            ? 'Try different keywords'
                                            : 'Add your first translation key'}
                                    </p>
                                    {!searchTerm && (
                                        <Button
                                            onClick={() => setIsAddModalOpen(true)}
                                            size="sm"
                                        >
                                            <Plus className="h-4 w-4 mr-2" />
                                            Add Key
                                        </Button>
                                    )}
                                </div>
                            ) : (
                                <div className="space-y-6 p-4">
                                    {sortedGroups.map((letter) => (
                                        <div key={letter} className="space-y-3">
                                            {/* Group Header */}
                                            <div className="flex items-center gap-2">
                                                <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-xs font-bold text-white">
                                                    {letter}
                                                </div>
                                                <div className="h-px flex-1 bg-border" />
                                            </div>
                                            {/* Grid of Cards */}
                                            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                                                {groupedTranslations[letter].map((translation, index) => (
                                                    <Card
                                                        key={index}
                                                        className="group relative overflow-hidden transition-all hover:shadow-md hover:border-primary/50"
                                                    >
                                                        <CardContent className="p-2">
                                                            {editingKey === translation.key ? (
                                                                // Editing mode
                                                                <div className="space-y-1">
                                                                    <div className="flex items-center gap-2">
                                                                        <div className="font-mono text-[10px] font-medium text-muted-foreground shrink-0">
                                                                            {translation.key}
                                                                        </div>
                                                                        <span className="text-muted-foreground shrink-0">⇒</span>
                                                                        <Input
                                                                            value={editingValue}
                                                                            onChange={(e) => setEditingValue(e.target.value)}
                                                                            className="h-7 text-xs flex-1 shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"
                                                                            autoFocus
                                                                            onKeyDown={(e) => {
                                                                                if (e.key === 'Enter') {
                                                                                    saveInlineEdit(translation.key);
                                                                                }
                                                                                if (e.key === 'Escape') {
                                                                                    cancelInlineEdit();
                                                                                }
                                                                            }}
                                                                        />
                                                                    </div>
                                                                    <div className="flex gap-1">
                                                                        <Button
                                                                            size="sm"
                                                                            onClick={() => saveInlineEdit(translation.key)}
                                                                            className="h-5 text-[10px] px-2 flex-1"
                                                                        >
                                                                            <Save className="h-2.5 w-2.5 mr-1" />
                                                                            Save
                                                                        </Button>
                                                                        <Button
                                                                            size="sm"
                                                                            variant="outline"
                                                                            onClick={cancelInlineEdit}
                                                                            className="h-5 text-[10px] px-2 flex-1"
                                                                        >
                                                                            Cancel
                                                                        </Button>
                                                                    </div>
                                                                </div>
                                                            ) : (
                                                                // View mode
                                                                <>
                                                                    <div className="flex items-start gap-2">
                                                                        <div className="font-mono text-[11px] font-medium text-primary shrink-0">
                                                                            {translation.key}
                                                                        </div>
                                                                        <span className="text-muted-foreground shrink-0">⇒</span>
                                                                        <div className="text-xs text-foreground line-clamp-2 flex-1 min-w-0">
                                                                            {translation.value}
                                                                        </div>
                                                                    </div>
                                                                    {/* Action Buttons */}
                                                                    <div className="absolute right-2 top-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                                                        <Button
                                                                            variant="ghost"
                                                                            size="icon"
                                                                            onClick={() => startInlineEdit(translation)}
                                                                            className="h-6 w-6 bg-background/80 backdrop-blur-sm"
                                                                        >
                                                                            <Edit2 className="h-3 w-3" />
                                                                        </Button>
                                                                        <AlertDialog>
                                                                            <AlertDialogTrigger asChild>
                                                                                <Button
                                                                                    variant="ghost"
                                                                                    size="icon"
                                                                                    className="h-6 w-6 bg-background/80 backdrop-blur-sm text-destructive hover:text-destructive"
                                                                                >
                                                                                    <Trash2 className="h-3 w-3" />
                                                                                </Button>
                                                                            </AlertDialogTrigger>
                                                                            <AlertDialogContent>
                                                                                <AlertDialogHeader>
                                                                                    <AlertDialogTitle>Delete Translation</AlertDialogTitle>
                                                                                    <AlertDialogDescription>
                                                                                        Delete key <strong className="font-mono">"{translation.key}"</strong>? This cannot be undone.
                                                                                    </AlertDialogDescription>
                                                                                </AlertDialogHeader>
                                                                                <AlertDialogFooter>
                                                                                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                                                                                    <AlertDialogAction
                                                                                        onClick={() => handleDeleteTranslation(translation.key)}
                                                                                        className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                                                                                    >
                                                                                        Delete
                                                                                    </AlertDialogAction>
                                                                                </AlertDialogFooter>
                                                                            </AlertDialogContent>
                                                                        </AlertDialog>
                                                                    </div>
                                                                </>
                                                            )}
                                                        </CardContent>
                                                    </Card>
                                                ))}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </ScrollArea>
                    </CardContent>
                </Card>
            </div>

            {/* Add Translation Modal */}
            <Dialog open={isAddModalOpen} onOpenChange={setIsAddModalOpen}>
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Add Translation Key</DialogTitle>
                        <DialogDescription>
                            Add a new key-value pair for {language.name}
                        </DialogDescription>
                    </DialogHeader>
                    <div className="space-y-3 py-3">
                        <div className="space-y-1.5">
                            <Label htmlFor="new-key" className="text-sm">Key</Label>
                            <Input
                                id="new-key"
                                placeholder="e.g., welcome_message"
                                value={newKey}
                                onChange={(e) => setNewKey(e.target.value)}
                                className="font-mono text-sm h-9"
                            />
                        </div>
                        <div className="space-y-1.5">
                            <Label htmlFor="new-value" className="text-sm">Value</Label>
                            <Textarea
                                id="new-value"
                                placeholder="Enter translation..."
                                value={newValue}
                                onChange={(e) => setNewValue(e.target.value)}
                                rows={3}
                                className="text-sm resize-none"
                            />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsAddModalOpen(false)} size="sm">
                            Cancel
                        </Button>
                        <Button onClick={handleAddTranslation} size="sm">
                            <Plus className="h-4 w-4 mr-2" />
                            Add
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Edit Translation Modal */}
            <Dialog open={isEditModalOpen} onOpenChange={setIsEditModalOpen}>
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Edit Translation</DialogTitle>
                        <DialogDescription>
                            Update the value for this key
                        </DialogDescription>
                    </DialogHeader>
                    <div className="space-y-3 py-3">
                        <div className="space-y-1.5">
                            <Label htmlFor="edit-key" className="text-sm">Key</Label>
                            <Input
                                id="edit-key"
                                value={editKey}
                                disabled
                                className="font-mono text-sm bg-muted h-9"
                            />
                        </div>
                        <div className="space-y-1.5">
                            <Label htmlFor="edit-value" className="text-sm">Value</Label>
                            <Textarea
                                id="edit-value"
                                placeholder="Enter translation..."
                                value={editValue}
                                onChange={(e) => setEditValue(e.target.value)}
                                rows={3}
                                className="text-sm resize-none"
                            />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsEditModalOpen(false)} size="sm">
                            Cancel
                        </Button>
                        <Button onClick={handleEditTranslation} size="sm">
                            <Save className="h-4 w-4 mr-2" />
                            Update
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
            </SettingsLayout>
        </>
    );
}

Translate.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Settings', href: route('settings.company.edit') },
            { title: 'Languages', href: route('language.index') },
            { title: 'Translate', href: '#' },
        ]}
        title="Manage Translations"
    >
        {page}
    </AppLayout>
);
