import { CardContent } from "@/Components/UI/Card"
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"
import { Button } from "@/Components/UI/Button"
import { Input } from "@/Components/UI/Input"
import { Label } from "@/Components/UI/Label"
import { Modal } from "@/Components/UI/Modal"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/Components/UI/Tabs"
import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from "@/Components/UI/Card"
import { useRef } from "react"
import { usePage, router } from '@inertiajs/react';
import { useState } from "react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/UI/Select"
import countries from "@/../data/countries.json";
import useTranslate from "@/hooks/useTranslate";
import { RSelect } from "@/Components/UI/RSelect"
import { toSelectOptions } from "@/Lib";
import { useDeleteHandler } from '@/hooks/useDeleteHandler';
import DeleteModal from "@/Components/DeleteModal"

export default function SettingsForm({ setup_data }) {



  const [isFileSubmitting, setIsFileSubmitting] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
  const [userToDelete, setUserToDelete] = useState(null)

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [verificationCode, setVerificationCode] = useState('');

  const { filePaths, auth } = usePage().props;

  const user = auth.user;

  const avatarUrl = user.avatar_url;
  const countryOptions = toSelectOptions(countries, "code", "name");
  const t = useTranslate()


  const userProfileConfig = filePaths?.profile?.user || {};
  const [width, height] = (userProfileConfig.size || '150x150').split('x');

  const fileInputRef = useRef(null)

  const handleButtonClick = () => {
    fileInputRef.current.click()
  }

  const handleFileChange = (event) => {
    setIsFileSubmitting(true)
    const file = event.target.files[0]
    if (file) {
      router.post(route('user.profile.avatar.update'), { image: file }, {
        onFinish: () => setIsFileSubmitting(false),
        onError: () => setIsFileSubmitting(false),
      })
    }
  }

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

  const { handleDelete, isDeleting } = useDeleteHandler('user.profile.delete', (deletedId) => {
    setIsDeleteModalOpen(false);
    setUserToDelete(null);
  });

  const [formData, setFormData] = useState({
    name: user?.name || "",
    email: user?.email || "",
    phone: user?.phone || "",
    phoneCode: user?.phone_code || "",
    country: user?.country_code || "",
  });

  const [passwordData, setPasswordData] = useState({
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  });

  function handleChange(e) {
    setFormData(prev => ({
      ...prev,
      [e.target.id]: e.target.value,
    }));
  }

  const handlePhoneCodeChange = (value) => {
    setFormData((prev) => ({
      ...prev,
      phoneCode: value,
    }))
  }

  const handleCountryChange = (value) => {
    setFormData((prev) => ({
      ...prev,
      country: value,
    }))
  }

  function handleSubmit(e) {
    e.preventDefault();

    setIsSubmitting(true)
    router.post(route('user.profile.update'), formData, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  function handlePasswordChange(e) {
    const { id, value } = e.target;
    setPasswordData(prev => ({
      ...prev,
      [id]: value,
    }));
  }


  function handlePasswordSubmit(e) {
    e.preventDefault();
    setIsSubmitting(true);

    router.post(
      route('user.password.update'),
      {
        current_password: passwordData.oldPassword,
        password: passwordData.newPassword,
        password_confirmation: passwordData.confirmPassword,
      },
      {
        onFinish: () => setIsSubmitting(false),
        onError: () => setIsSubmitting(false),
      }
    );
  }


  const handleEnable2FA = () => {
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setVerificationCode('');
  };

  const handle2FASubmit = () => {

    router.post(route("user.2fa.verify"), {
      code: verificationCode
    })
    handleCloseModal();
  };



  return (
    <div className="flex-1 p-3 sm:p-4 lg:p-6 overflow-auto bg-gray-50 dark:bg-black">
      {/* Settings Header */}
      <div className="space-y-1 mb-4 sm:mb-6">
        <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">{t("Profile Settings")}</h1>
        <p className="text-sm sm:text-base text-gray-500 dark:text-gray-200">{t("Manage your profile here")}</p>
      </div>

      {/* Tabs Component - Mobile friendly */}
      <Tabs defaultValue="profile">
        <div className="overflow-x-auto mb-4 sm:mb-6">
          <TabsList className="inline-flex bg-white dark:bg-zinc-900 rounded-lg p-1 gap-1 shadow-sm min-w-max">
            <TabsTrigger
              value="profile"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium transition-colors whitespace-nowrap"
            >
              Profile
            </TabsTrigger>
            <TabsTrigger
              value="password"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium transition-colors whitespace-nowrap"
            >
              Password
            </TabsTrigger>
            <TabsTrigger
              value="security"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-2 sm:px-3 py-1.5 text-xs sm:text-sm font-medium transition-colors whitespace-nowrap"
            >
              Security
            </TabsTrigger>
          </TabsList>
        </div>

        {/* Tabs Content for Profile */}
        <TabsContent value="profile" className="mt-4 sm:mt-6">
          <Card className="bg-white dark:bg-zinc-900">
            <CardContent className="p-4 sm:p-6 space-y-4 sm:space-y-6">
              <div className="flex flex-col sm:flex-row items-center space-y-4 sm:space-y-0 sm:space-x-4">
                <Avatar className="h-16 w-16 sm:h-20 sm:w-20">
                  <AvatarImage src={avatarUrl} alt="User Avatar" />
                  <AvatarFallback className="bg-gradient-to-br from-primary to-secondary text-white font-bold text-lg sm:text-xl">
                    {user?.name
                      ?.split(" ")
                      .map((n) => n[0])
                      .join("")
                      .toUpperCase()
                      .slice(0, 2) || "U"}
                  </AvatarFallback>
                </Avatar>

                <Input
                  type="file"
                  ref={fileInputRef}
                  className="hidden"
                  accept="image/*"
                  onChange={handleFileChange}
                />

                <Button
                  isLoading={isFileSubmitting}
                  variant="outline"
                  className=""
                  onClick={handleButtonClick}
                >
                  {isFileSubmitting ? t("Uploading...") : t("Upload")}
                </Button>
              </div>
              <form onSubmit={handleSubmit}>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                  <div className="space-y-2">
                    <Label htmlFor="name">{t("Name")}</Label>
                    <Input
                      id="name"
                      placeholder="Enter name"
                      value={formData.name}
                      onChange={handleChange}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="email">{t("Email")}</Label>
                    <Input
                      id="email"
                      type="email"
                      placeholder="Enter email"
                      value={formData.email}
                      onChange={handleChange}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="phone">{t("Phone Number")}</Label>
                    <Input
                      id="phone"
                      type="tel"
                      placeholder={t("Input your phone")}
                      value={formData.phone}
                      onChange={handleChange}
                      className="bg-white border-gray-300 text-gray-900 dark:bg-zinc-800 dark:border-zinc-700 dark:text-white focus:border-primary dark:focus:border-primary"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="country">{t("Country")}</Label>
                    <RSelect
                      options={countryOptions}
                      value={formData.country}
                      onChange={handleCountryChange}
                      placeholder={t("Select country")}
                    />
                  </div>
                </div>
                <div className="flex justify-start space-x-4 pt-4">

                  <Button
                    isLoading={isSubmitting}
                    className="bg-gradient-to-r from-primary to-secondary text-white rounded-md px-6 py-2 hover:from-secondary hover:to-primary"
                  >
                    {isSubmitting ? t("Submiting...") : t("Submit")}
                  </Button>
                </div>
              </form>

            </CardContent>
          </Card>
        </TabsContent>

        {/* Tabs Content for Password */}
        <TabsContent value="password" className="mt-6">
          <Card className="bg-white">
            <CardContent className="p-6">
              <form onSubmit={handlePasswordSubmit} className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="old-password">{t("Old Password")}</Label>
                  <Input
                    id="oldPassword"
                    type="password"
                    placeholder="Enter old password"
                    value={passwordData.oldPassword}
                    onChange={handlePasswordChange}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="new-password">{t("New Password")}</Label>
                  <Input
                    id="newPassword"
                    type="password"
                    placeholder="Enter new password"
                    value={passwordData.newPassword}
                    onChange={handlePasswordChange}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="confirm-password">{t("Confirm Password")}</Label>
                  <Input
                    id="confirmPassword"
                    type="password"
                    placeholder="Confirm new password"
                    value={passwordData.confirmPassword}
                    onChange={handlePasswordChange}
                  />
                </div>
                <div className="flex justify-start space-x-4 pt-4">
                  <Button
                    isLoading={isSubmitting}
                    className="bg-gradient-to-r from-primary to-secondary text-white rounded-md px-6 py-2 hover:from-secondary hover:to-primary"
                  >
                    {isSubmitting ? t("Submiting...") : t("Submit")}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Tabs Content for Security */}
        <TabsContent value="security" className="mt-6">
          <Card className="bg-white">
            <CardContent className="p-6">
              <div className="space-y-6">
                <div className="flex items-center justify-start">
                  <span className="text-black dark:text-gray-200 text-sm mr-2 font-bold">{t("Two-Factor Authentication")}</span>
                  <span
                    className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${user.two_factor_enabled
                        ? "bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-200"
                        : "bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200"
                      }`}
                  >
                    {user.two_factor_enabled ? t("Enabled") : t("Disabled")}
                  </span>

                </div>
                <p className="text-gray-500 dark:text-gray-200 text-sm">
                  {t("Keep your account extra secure with a second authentication step. In addition to your password, you'll have to enter a code (delivered via authenticator app or email) to log into your account.")}
                </p>
                <Button className="bg-white dark:bg-zinc-800 text-teal-500 border border-teal-500 hover:bg-teal-50" onClick={handleEnable2FA}>
                  {t("Enable 2FA")}
                </Button>
              </div>
            </CardContent>
          </Card>

          <Modal
            isOpen={isModalOpen}
            onClose={handleCloseModal}
            title={t("Scan QR Code")}
            onSubmit={handle2FASubmit}
          >
            <p className="text-gray-500 dark:text-gray-200 text-sm mb-4">
              {t("Scan this QR code with an authenticator app like: Google Authenticator, Authy, Microsoft Authenticator or 1Password. It will display a 6 digit code which you need to enter below.")}
            </p>
            <div className="flex justify-center mb-4">
              {setup_data?.qr_code ? (
                <img
                  src={setup_data.qr_code}
                  alt="QR Code"
                  className="w-48 h-48"
                  style={{ width: '200px', height: '200px' }}
                />
              ) : (
                <p>{t("QR code not available")}</p>
              )}
            </div>
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">{t("Verification Code")}</label>
              <Input
                type="text"
                value={verificationCode}
                onChange={(e) => setVerificationCode(e.target.value)}
                placeholder="Enter Code"
                className="w-full p-2 border rounded-md"
              />
            </div>
          </Modal>
        </TabsContent>
      </Tabs>

      {/* Danger Zone Card (outside of Tabs, as it's a separate section) */}
      {/* Only show danger zone if user is not an owner */}
      {user?.owner !== '1' && user?.owner !== 1 && (
        <Card className="mt-8 border-red-300 bg-red-50 dark:bg-zinc-900">
          <CardHeader>
            <CardTitle className="text-red-700">{t("Danger Zone")}</CardTitle>
            <CardDescription className="text-red-600">
              {t("Deleting this account will delete it permanently from your account and you won&apos;t be able to access it anymore.")}
            </CardDescription>
          </CardHeader>
          <CardFooter>
            <Button
              onClick={handleDeleteClick}
              className="bg-red-500 text-white hover:bg-red-600 rounded-md px-6 py-2"
            >
              {t("Delete Account")}
            </Button>
          </CardFooter>
        </Card>
      )}

      {/* Owner protection message */}
      {(user?.owner === '1' || user?.owner === 1) && (
        <Card className="mt-8 border-blue-300 bg-blue-50 dark:bg-zinc-900">
          <CardHeader>
            <CardTitle className="text-blue-700 flex items-center gap-2">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
              </svg>
              {t("Owner Account Protection")}
            </CardTitle>
            <CardDescription className="text-blue-600">
              {t("This is the owner account and cannot be deleted. To delete this account, you must first transfer ownership to another user.")}
            </CardDescription>
          </CardHeader>
        </Card>
      )}

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