import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { Loader2, Lock } from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/shared/common/ui/form";
import { Input } from "@/shared/common/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Switch } from "@/shared/common/ui/switch";
import { toast } from "sonner";
import {
  usePasswordSettingsQuery,
  usePasswordSettingsMutations,
} from "../../hooks/usePasswordSettings";
import { PasswordSettings } from "../../services/api/passwordSettingsService";
import Loader from "@/record-management/components/Loader/loader";

interface PasswordSettingsFormValues {
  minimumPasswordLength: number;
  maximumPasswordLength: number;
  passwordExpiry: number;
  sessionTimeout: number;
  isDefaultPasswordEnabled: boolean;
  defaultPassword: string;
}

interface PasswordSettingsFormProps {
  onSuccessCallback?: () => void;
  isDialogForm?: boolean;
}

export default function PasswordSettingsForm({
  onSuccessCallback,
  isDialogForm = false,
}: PasswordSettingsFormProps) {
  const { t } = useTranslation();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { data: settings, isLoading, error } = usePasswordSettingsQuery();
  const mutations = usePasswordSettingsMutations();

  const form = useForm<PasswordSettingsFormValues>({
    defaultValues: {
      minimumPasswordLength: 8,
      maximumPasswordLength: 64,
      passwordExpiry: 90,
      sessionTimeout: 30,
      isDefaultPasswordEnabled: false,
      defaultPassword: "Welcome@123",
    },
  });

  useEffect(() => {
    if (settings) {
      form.reset({
        minimumPasswordLength: settings.minimumPasswordLength || 8,
        maximumPasswordLength: settings.maximumPasswordLength || 64,
        passwordExpiry: settings.passwordExpiry || 90,
        sessionTimeout: settings.sessionTimeout || 30,
        isDefaultPasswordEnabled: settings.isDefaultPasswordEnabled || false,
        defaultPassword: settings.defaultPassword || "Welcome@123",
      });
    }
  }, [settings, form]);

  const onSubmit = async (values: PasswordSettingsFormValues) => {
    if (values.minimumPasswordLength > values.maximumPasswordLength) {
      toast.error(
        t(
          "passwordSettings.minMaxError",
          "Minimum password length cannot be greater than maximum"
        )
      );
      return;
    }

    if (
      values.isDefaultPasswordEnabled &&
      !values.defaultPassword?.trim()
    ) {
      toast.error(
        t(
          "passwordSettings.defaultPasswordRequired",
          "Default password is required when enabled"
        )
      );
      return;
    }

    setIsSubmitting(true);
    try {
      const payload: PasswordSettings = {
        ...values,
        id: settings?.id,
      };

      if (settings?.id) {
        await mutations.update.mutateAsync(payload);
      } else {
        await mutations.create.mutateAsync(payload);
      }
      
      // Call success callback if provided (for dialog form)
      if (onSuccessCallback) {
        onSuccessCallback();
      }
      
      // Reset form after successful submission
      form.reset();
    } catch (error) {
      // Error is handled by the hook
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoading) {
    return <Loader />;
  }

  if (error) {
    return (
      <Card className="border-red-200">
        <CardHeader>
          <CardTitle className="text-red-600">
            {t("passwordSettings.error", "Error Loading Settings")}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-gray-600">
            {t(
              "passwordSettings.errorMessage",
              "Failed to load password settings. Please try again."
            )}
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className={isDialogForm ? "w-full border-0 shadow-none" : "w-full"}>
      {!isDialogForm && (
        <CardHeader>
          <div className="flex items-center gap-2">
            <Lock className="w-5 h-5 text-primary" />
            <div>
              <CardTitle>
                {t("passwordSettings.title", "Password Settings")}
              </CardTitle>
              <CardDescription>
                {t(
                  "passwordSettings.description",
                  "Configure password policies and security settings for your organization"
                )}
              </CardDescription>
            </div>
          </div>
        </CardHeader>
      )}

      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            {/* Password Length Section */}
            <div className="space-y-4 p-4 bg-gray-50 rounded-lg border border-gray-200 dark:bg-gray-900 dark:border-gray-800">
              <h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <Lock className="w-4 h-4" />
                {t("passwordSettings.passwordLength", "Password Length Requirements")}
              </h3>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="minimumPasswordLength"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        {t(
                          "passwordSettings.minimumLength",
                          "Minimum Password Length"
                        )}
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min="1"
                          max="100"
                          {...field}
                          onChange={(e) =>
                            field.onChange(parseInt(e.target.value))
                          }
                          disabled={isSubmitting}
                        />
                      </FormControl>
                      <FormDescription className="text-xs">
                        {t("passwordSettings.minimumLengthDesc", "Minimum: 1, Recommended: 8")}
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="maximumPasswordLength"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        {t(
                          "passwordSettings.maximumLength",
                          "Maximum Password Length"
                        )}
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min="1"
                          max="256"
                          {...field}
                          onChange={(e) =>
                            field.onChange(parseInt(e.target.value))
                          }
                          disabled={isSubmitting}
                        />
                      </FormControl>
                      <FormDescription className="text-xs">
                        {t("passwordSettings.maximumLengthDesc", "Maximum: 256, Recommended: 64")}
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            {/* Password Expiry Section */}
            <div className="space-y-4 p-4 bg-gray-50 rounded-lg border border-gray-200 dark:bg-gray-900 dark:border-gray-800">
              <h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <Lock className="w-4 h-4" />
                {t("passwordSettings.passwordExpiry", "Password Expiry Policy")}
              </h3>

              <FormField
                control={form.control}
                name="passwordExpiry"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t(
                        "passwordSettings.passwordExpiryDays",
                        "Password Expiry (Days)"
                      )}
                    </FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min="0"
                        max="365"
                        {...field}
                        onChange={(e) =>
                          field.onChange(parseInt(e.target.value))
                        }
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormDescription>
                      {t(
                        "passwordSettings.passwordExpiryDesc",
                        "Number of days before passwords expire (0 = never expires)"
                      )}
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Session Timeout Section */}
            <div className="space-y-4 p-4 bg-gray-50 rounded-lg border border-gray-200 dark:bg-gray-900 dark:border-gray-800">
              <h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <Lock className="w-4 h-4" />
                {t("passwordSettings.sessionManagement", "Session Management")}
              </h3>

              <FormField
                control={form.control}
                name="sessionTimeout"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t(
                        "passwordSettings.sessionTimeout",
                        "Session Timeout (Minutes)"
                      )}
                    </FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min="1"
                        max="1440"
                        {...field}
                        onChange={(e) =>
                          field.onChange(parseInt(e.target.value))
                        }
                        disabled={isSubmitting}
                      />
                    </FormControl>
                    <FormDescription>
                      {t(
                        "passwordSettings.sessionTimeoutDesc",
                        "Idle session timeout in minutes (1 minute to 24 hours)"
                      )}
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Default Password Section */}
            <div className="space-y-4 p-4 bg-gray-50 rounded-lg border border-gray-200 dark:bg-gray-900 dark:border-gray-800">
              <h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <Lock className="w-4 h-4" />
                {t("passwordSettings.defaultPassword", "Default Password")}
              </h3>

              <FormField
                control={form.control}
                name="isDefaultPasswordEnabled"
                render={({ field }) => (
                  <FormItem className="flex items-center justify-between rounded-lg border border-gray-200 p-3 dark:border-gray-800">
                    <div className="space-y-0.5">
                      <FormLabel>
                        {t(
                          "passwordSettings.enableDefaultPassword",
                          "Enable Default Password"
                        )}
                      </FormLabel>
                      <FormDescription>
                        {t(
                          "passwordSettings.enableDefaultPasswordDesc",
                          "Use a default password for new users"
                        )}
                      </FormDescription>
                    </div>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                        disabled={isSubmitting}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />

              {form.watch("isDefaultPasswordEnabled") && (
                <FormField
                  control={form.control}
                  name="defaultPassword"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        {t(
                          "passwordSettings.defaultPasswordValue",
                          "Default Password"
                        )}
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="password"
                          placeholder="Enter default password"
                          {...field}
                          disabled={isSubmitting}
                        />
                      </FormControl>
                      <FormDescription className="text-xs">
                        {t(
                          "passwordSettings.defaultPasswordValueDesc",
                          "This password will be used for newly created user accounts"
                        )}
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}
            </div>

            {/* Buttons */}
            <div className="flex justify-end gap-3 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => form.reset()}
                disabled={isSubmitting}
              >
                {t("common.reset", "Reset")}
              </Button>
              <Button
                type="submit"
                disabled={isSubmitting}
                className="bg-primary hover:bg-primary-700"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    {t("common.saving", "Saving")}
                  </>
                ) : (
                  t("common.save", "Save Changes")
                )}
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  );
}
