"use client"

import { useState, useEffect } from "react"
import DataTable from "@/Components/DataTable"
import { Switch } from "@/Components/UI/Switch"
import { Badge , badgeVariants} from "@/Components/UI/Badge"
import { CountryFlag } from "@/Components/UI/CountryFlag"
import { Input } from "@/Components/UI/Input"
import { LanguagesIcon, Star, Trash2, Sparkle, Plus, Zap, Search } from "lucide-react"
import countries from "@/../data/countries.json";
import { useDeleteHandler } from '@/hooks/useDeleteHandler';
import { useToggleHandler } from '@/hooks/useToggleHandler';
import { useBulkHandler } from '@/hooks/useBulkHandler';
import DeleteModal from "@/Components/DeleteModal"
import { Modal } from "@/Components/UI/Modal"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/UI/Select"
import { router } from "@inertiajs/react"
import useTranslate from "@/hooks/useTranslate";
import toast from "react-hot-toast";

export default function Languages({ languages, isModalOpen, setIsModalOpen }) {
  const [languageList, setLanguageList] = useState(languages?.data || []);
  const [internalModalOpen, setInternalModalOpen] = useState(false);

  // Use external modal state if provided, otherwise use internal state
  const modalOpen = isModalOpen !== undefined ? isModalOpen : internalModalOpen;
  const setModalOpen = setIsModalOpen || setInternalModalOpen;
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
  const [languageToDelete, setLanguageToDelete] = useState(null)
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

  const t = useTranslate();

  const [languageData, setLanguageData] = useState({
    name: "",
    code: "",
    ltr: "",
    lang_code : ""
  });
  const [countrySearch, setCountrySearch] = useState("");

  // Filter countries based on search
  const filteredCountries = countries.filter(country =>
    country.name.toLowerCase().includes(countrySearch.toLowerCase()) ||
    country.code.toLowerCase().includes(countrySearch.toLowerCase()) ||
    country.lang.toLowerCase().includes(countrySearch.toLowerCase())
  );

  useEffect(() => {
    setLanguageList(languages?.data || [])
  }, [languages]);



  const columns = [
    {
      key: "id",
      label: "No",
      className: "w-16",
      cellClassName: "font-medium text-gray-900 dark:text-neutral-200",
      render: (_item, index) => index + 1,
    },
    {
      key: "name",
      label: "Name",
      render: (item) => (
        <div className="flex items-center gap-3">
          <CountryFlag code={item.code}  size="32px"/>
          <span className="font-medium text-gray-900 dark:text-neutral-200">{item.name}</span>
          {item.is_default === "1" && (
            <Badge className="bg-gradient-to-r from-primary to-secondary text-white">Default</Badge>
          )}
        </div>
      ),
    },
    {
      key: "status",
      label: "Status",
      className: "w-24",
      render: (item) => (
        <Switch
          checked={item.status === '1'}
          onCheckedChange={() => handleToggleLanguage(item.id)}
          className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-sky-400 data-[state=checked]:to-cyan-400"
        />
      ),
    },
    {
      key: "lang_code",
      label: "Lang Code",
      className: "w-22",
      cellClassName: "font-mono text-gray-600 dark:text-neutral-200",
    },
    {
      key: "ltr",
      label: "LTR/RTL",
      className: "w-22",
      cellClassName: "font-mono text-gray-600 dark:text-neutral-200",
      render : (item) => (
        <div className="flex items-center gap-3">
          <span className="font-medium text-gray-900 dark:text-neutral-200">{item.ltr === '1' ? 'LTR' : 'RTL'}</span>
         
        </div>
      ),
    }
  ]

  const actionMenuItems = [
    {
      key: "translate",
      label: "Translate",
      icon: LanguagesIcon,
    },
    {
      key: "auto-translate",
      label: "Auto Translate",
      icon: Zap,
    },
    {
      key: "make-default",
      label: "Make Default",
      icon: Star,
    },
    {
      key: "delete",
      label: "Delete",
      icon: Trash2,
    },
  ]

  const searchFields = ["name", "code"]

  const filterOptions = [
    {
      value: "1",
      label: "Active",
      filterFn: (item) => item.status === "1",
    },
    {
      value: "0",
      label: "Inactive",
      filterFn: (item) => item.status === "0",
    },
  ]


  const { handleToggle, isToggling } = useToggleHandler('user.language.status.update', (id, newStatus) => {
    setLanguageList((prev) =>
      prev.map((language) =>
        language.id === id ? { ...language, status: newStatus } : language,
      ),
    );
  });

  const handleToggleLanguage = (languageId) => {
    const language = languageList.find((l) => l.id === languageId);
    if (language) {
      handleToggle(languageId, language.status);
    }
  };

  const handleCreateLanguage = () => {
    router.post(route('user.language.store'), languageData, {
      onSuccess: () => {
        setModalOpen(false);
        resetForm();
      }
    });
  };

  const resetForm = () => {
    setLanguageData({
      name: "",
      code: "",
      ltr: "",
      lang_code: ""
    });
    setCountrySearch("");
  };

  const openModal = () => {
    resetForm();
    setModalOpen(true);
  };

  const closeModal = () => {
    setModalOpen(false);
    resetForm();
  };

  const handleInputChange = (field, value) => {
    setLanguageData(prev => {
      let updated = { ...prev, [field]: value };

      if (field === "code") {
        const country = countries.find(c => c.code === value);
        if (country) {
          updated.name = country.name;
          updated.lang_code = country.language_code
        }
      }

      return updated;
    });
  };



  const handleDeleteClick = (language) => {
    setLanguageToDelete(language)
    setIsDeleteModalOpen(true)
  }

  const { handleDelete, isDeleting } = useDeleteHandler('user.language.delete', (deletedId) => {
    setLanguageList((prev) => prev.filter((l) => l.id !== deletedId));
    setIsDeleteModalOpen(false);
    setLanguageToDelete(null);
  });

  const { handleBulkAction, isBulkProcessing } = useBulkHandler(
    "user.language.bulk",
    (action, ids, statusEnum) => {
      setLanguageList((prev) => {
        // Ensure prev is an array
        if (!Array.isArray(prev)) {
          return [];
        }
        
        switch (action) {
          case "active":
            return prev.map((l) =>
              ids.includes(l.id) ? { ...l, status: statusEnum?.Active || "1" } : l
            )
          case "inactive":
            return prev.map((l) =>
              ids.includes(l.id) ? { ...l, status: statusEnum?.Inactive || "0" } : l
            )
          case "delete":
            return prev.filter((l) => !ids.includes(l.id))
          default:
            return prev
        }
      })
    }
  )


  const handleSearch = (value) => {
    setSearchQuery(value);

    router.get(
      route("user.setting.index"),
      {
        search: value,
        status: statusFilter !== "all" ? statusFilter : undefined,
        page: 1,
      },
      { preserveState: true, replace: true }
    );
  };


  const handleFilter = (value) => {
    setStatusFilter(value);

    router.get(
      route("user.setting.index"),
      {
        search: searchQuery,
        status: value !== "all" ? value : undefined,
        page: 1,
      },
      { preserveState: true, replace: true }
    );
  };

  const handleRowAction = (action, language) => {
    switch (action) {
      case "translate":
        handleTranslate(language.id)
        break
      case "auto-translate":
        handleAutoTranslate(language.id, language.lang_code)
        break
      case "make-default":
        // Don't allow making default if already default
        if (language.is_default !== "1") {
          handleMakeDefault(language.id)
        }
        break
      case "delete":
        // Don't allow deleting default language
        if (language.is_default !== "1") {
          handleDeleteClick(language)
        } else {
          // Could show a toast or alert here
          console.warn("Cannot delete default language")
        }
        break
    }
  }

  const handleMakeDefault = (languageId) => {
    router.post(route('user.language.make.default'), { id: languageId }, {
      preserveState: true,
      preserveScroll: true,
    })
  }

  const handleTranslate = (languageId) => {
    router.get(route('user.language.translation'), { id: languageId }, {
      preserveState: true,
      preserveScroll: true,
    })
  }

  const handleAutoTranslate = (languageId, langCode) => {
    if (confirm(`Auto-translate all text to ${languageList.find(l => l.id === languageId)?.name}? This will replace existing translations.`)) {
      router.post(route('user.language.auto-translate'), { 
        id: languageId, 
        lang_code: langCode 
      }, {
        preserveState: true,
        preserveScroll: true,
        onSuccess: () => {
          toast.success('Auto-translation completed successfully!')
        },
        onError: () => {
          toast.error('Auto-translation failed. Please try again.')
        }
      })
    }
  }

  return (
    <>
      <DataTable
        data={languageList}
        columns={columns}
        searchFields={searchFields}
        searchPlaceholder={t("Search by name or code")}
        filterOptions={filterOptions}
        actionMenuItems={actionMenuItems}
        onSearch={handleSearch}
        onFilterChange={handleFilter}
        onBulkActive={(ids) => handleBulkAction("active", ids)}
        onBulkInactive={(ids) => handleBulkAction("inactive", ids)}
        onBulkDelete={(ids) => handleBulkAction("delete", ids)}
        onRowAction={handleRowAction}
        paginationData={{ links: languages.links, currentPage: languages.current_page, lastPage: languages.last_page }}
        className="border-0 shadow-none p-0"
      />

      {/* Language Create Modal */}
      <Modal
        isOpen={modalOpen}
        onClose={closeModal}
        onSubmit={handleCreateLanguage}
        title={
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-gradient-to-r from-primary to-secondary rounded-lg flex items-center justify-center">
              <Sparkle className="w-4 h-4 text-white" />
            </div>
            <span>{t("Create Language")}</span>
          </div>
        }
        submitText="Create Language"
        className="max-w-md"
        width="w-[26rem]"
        buttonWidth="w-full"
      >
        <div className="space-y-6">
          {/* Description */}
          <div className="text-center">
            <p className="text-gray-500 dark:text-gray-400 text-sm">
              {t("Select a language and text direction for your app.")}
            </p>
          </div>

          {/* Form Fields */}
          <div className="space-y-4">
            {/* Language Select with Search */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Language</label>
              <div className="relative">
                <Input
                  type="text"
                  placeholder="Search countries..."
                  value={countrySearch}
                  onChange={(e) => setCountrySearch(e.target.value)}
                  className="w-full bg-gray-50 border-gray-200 pr-10"
                />
                <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              </div>
              
              {/* Selected Country Display */}
              {languageData.code && (
                <div className="mt-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center gap-3">
                    <CountryFlag code={languageData.code} size="24px" />
                    <div>
                      <span className="font-medium text-blue-900">{languageData.name}</span>
                      <div className="text-sm text-blue-600">
                        Code: {languageData.code} | Language: {countries.find(c => c.code === languageData.code)?.lang}
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Country Dropdown */}
              {countrySearch && (
                <div className="mt-1 max-h-60 overflow-y-auto bg-white border border-gray-200 rounded-lg shadow-lg">
                  {filteredCountries.length > 0 ? (
                    filteredCountries.slice(0, 20).map((country) => (
                      <div
                        key={country.code}
                        onClick={() => {
                          handleInputChange("code", country.code);
                          setCountrySearch("");
                        }}
                        className="flex items-center gap-3 p-3 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-b-0"
                      >
                        <CountryFlag code={country.code} size="24px" />
                        <div className="flex-1">
                          <div className="font-medium text-gray-900">{country.name}</div>
                          <div className="text-sm text-gray-500">
                            {country.code} • {country.lang}
                          </div>
                        </div>
                      </div>
                    ))
                  ) : (
                    <div className="p-4 text-center text-gray-500">
                      No countries found matching "{countrySearch}"
                    </div>
                  )}
                  {filteredCountries.length > 20 && (
                    <div className="p-3 text-center text-sm text-gray-500 bg-gray-50">
                      Showing first 20 results. Keep typing to narrow down...
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Text Direction (LTR/RTL) */}
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Text Direction</label>
              <Select
                value={languageData.ltr !== undefined ? String(languageData.ltr) : ""}
                onValueChange={(value) => handleInputChange("ltr", (value))}
              >
                <SelectTrigger className="w-full bg-gray-50 border-gray-200">
                  <SelectValue placeholder="Select direction" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">LTR</SelectItem>
                  <SelectItem value="0">RTL</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
      </Modal>


      {/* Delete Modal */}
      <DeleteModal
        isOpen={isDeleteModalOpen}
        onClose={() => setIsDeleteModalOpen(false)}
        title="Delete this Language?"
        description="Are you really sure you want to delete this language?"
        onConfirm={() => handleDelete(languageToDelete?.id)}
        isDeleting={isDeleting}
      />
    </>



  )
}
