import React, { useState, useEffect } from 'react'; 
import AppLayout from "@/Layouts/AppLayout";
import { Head } from '@inertiajs/react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/Components/UI/Card";
import { Button } from "@/Components/UI/Button";
import { Input } from "@/Components/UI/Input";
import { Label } from "@/Components/UI/Label";
import { CountryFlag } from "@/Components/UI/CountryFlag";
import { Plus, Save, Trash2, Languages, ArrowLeft } from 'lucide-react';
import { router } from '@inertiajs/react';
import toast from "react-hot-toast";
import useTranslate from "@/hooks/useTranslate";

export default function LanguageTranslation({ auth, language, translations = {} }) {
    const [translationData, setTranslationData] = useState(translations);
    const [newTranslations, setNewTranslations] = useState([{ key: '', value: '' }]);
    const [isLoading, setIsLoading] = useState(false);

    const t = useTranslate();

    const breadcrumbs = [
        { label: t("Settings"), href: route("user.setting.index") },
        { label: t("Languages") },
        { label: language.name }
    ];

    const handleExistingTranslationChange = (key, value) => {
        setTranslationData(prev => ({
            ...prev,
            [key]: value
        }));
    };

    const handleNewTranslationChange = (index, field, value) => {
        setNewTranslations(prev => 
            prev.map((item, i) => 
                i === index ? { ...item, [field]: value } : item
            )
        );
    };

    const addNewTranslationRow = () => {
        setNewTranslations(prev => [...prev, { key: '', value: '' }]);
    };

    const removeNewTranslationRow = (index) => {
        setNewTranslations(prev => prev.filter((_, i) => i !== index));
    };

    const handleSave = () => {
        setIsLoading(true);

        // Combine existing and new translations
        const validNewTranslations = newTranslations.filter(t => t.key.trim() && t.value.trim());
        const allTranslations = { ...translationData };

        // Add new translations
        validNewTranslations.forEach(t => {
            allTranslations[t.key.trim()] = t.value.trim();
        });

        // Convert to the format expected by the controller
        const translationsArray = Object.entries(allTranslations).map(([key, value]) => ({
            key,
            value
        }));

        router.post(route('user.language.translation.add'), {
            translations: translationsArray,
            language_id: language.id
        }, {
            preserveState: true,
            preserveScroll: true,
            onSuccess: () => {
                toast.success(t("Translations saved successfully"));
                setNewTranslations([{ key: '', value: '' }]);
                setIsLoading(false);
            },
            onError: () => {
                toast.error(t("Failed to save translations"));
                setIsLoading(false);
            }
        });
    };

    const goBack = () => {
        router.get(route('user.setting.index'));
    };

    return (
        <AppLayout user={auth.user} breadcrumbs={breadcrumbs}>
            <Head title={`${t("Translations")} - ${language.name}`} />

            <div className="py-6">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    {/* Header */}
                    <div className="mb-6">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-4">
                                <Button
                                    variant="ghost"
                                    size="icon"
                                    onClick={goBack}
                                    className="h-10 w-10"
                                >
                                    <ArrowLeft className="h-5 w-5" />
                                </Button>
                                <div className="flex items-center gap-3">
                                    <div>
                                        <Languages className="h-6 w-6 text-primary" />
                                    </div>
                                    <div>
                                        <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">
                                            {t("Language Translations")}
                                        </h1>
                                        <p className="text-gray-500 dark:text-gray-200">
                                            Customize and manage language translations for your application
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <Button 
                                onClick={handleSave}
                                disabled={isLoading}
                                className="bg-gradient-to-r from-primary to-secondary hover:opacity-90"
                            >
                                <Save className="w-4 h-4 mr-2" />
                                {isLoading ? t("Saving...") : t("Save Changes")}
                            </Button>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        {/* Existing Translations */}
                        <Card className="border-0 shadow-sm bg-white/50 dark:bg-zinc-900/50 backdrop-blur-sm">
                            <CardHeader>
                                <CardTitle className="flex items-center space-x-2">
                                    <Languages className="w-5 h-5" />
                                    <span>{t("Existing Translations")}</span>
                                </CardTitle>
                                <CardDescription>
                                    {t("Edit existing translation values")}
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                {Object.entries(translationData).length === 0 ? (
                                    <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                                        <Languages className="w-12 h-12 mx-auto mb-3 opacity-50" />
                                        <p>{t("No translations found")}</p>
                                        <p className="text-sm">{t("Add new translations using the form on the right")}</p>
                                    </div>
                                ) : (
                                    Object.entries(translationData).map(([key, value]) => (
                                        <div key={key} className="space-y-2">
                                            <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                                {key}
                                            </Label>
                                            <Input
                                                value={value}
                                                onChange={(e) => handleExistingTranslationChange(key, e.target.value)}
                                                placeholder={t("Translation value")}
                                                className="bg-white dark:bg-zinc-800"
                                            />
                                        </div>
                                    ))
                                )}
                            </CardContent>
                        </Card>

                        {/* Add New Translations */}
                        <Card className="border-0 shadow-sm bg-white/50 dark:bg-zinc-900/50 backdrop-blur-sm">
                            <CardHeader>
                                <CardTitle className="flex items-center justify-between">
                                    <div className="flex items-center space-x-2">
                                        <Plus className="w-5 h-5" />
                                        <span>{t("Add New Translations")}</span>
                                    </div>
                                    <Button 
                                        variant="outline" 
                                        size="sm"
                                        onClick={addNewTranslationRow}
                                    >
                                        <Plus className="w-4 h-4 mr-1" />
                                        {t("Add Row")}
                                    </Button>
                                </CardTitle>
                                <CardDescription>
                                    {t("Add new translation keys and values")}
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                {newTranslations.map((translation, index) => (
                                    <div key={index} className="flex space-x-2">
                                        <div className="flex-1">
                                            <Input
                                                value={translation.key}
                                                onChange={(e) => handleNewTranslationChange(index, 'key', e.target.value)}
                                                placeholder={t("Translation key")}
                                                className="bg-white dark:bg-zinc-800"
                                            />
                                        </div>
                                        <div className="flex-1">
                                            <Input
                                                value={translation.value}
                                                onChange={(e) => handleNewTranslationChange(index, 'value', e.target.value)}
                                                placeholder={t("Translation value")}
                                                className="bg-white dark:bg-zinc-800"
                                            />
                                        </div>
                                        {newTranslations.length > 1 && (
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                onClick={() => removeNewTranslationRow(index)}
                                                className="text-red-500 hover:text-red-700"
                                            >
                                                <Trash2 className="w-4 h-4" />
                                            </Button>
                                        )}
                                    </div>
                                ))}
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}