"use client";

import { AuthorizedAction } from "@/components/auth/authorized-action";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogBody,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useTranslations } from "next-intl";
import type { UpdateManualStatisticsInput, AccountStatistics } from "@/types";
import { useEffect } from "react";

const statisticsSchema = z.object({
  followers_count: z.coerce.number().min(0).optional(),
  following_count: z.coerce.number().min(0).optional(),
  posts_count: z.coerce.number().min(0).optional(),
  total_reach: z.coerce.number().min(0).optional(),
  total_impressions: z.coerce.number().min(0).optional(),
  total_views: z.coerce.number().min(0).optional(),
  total_likes: z.coerce.number().min(0).optional(),
  total_comments: z.coerce.number().min(0).optional(),
  total_shares: z.coerce.number().min(0).optional(),
  engagement_rate: z.coerce.number().min(0).optional(),
  growth_rate: z.coerce.number().min(0).optional(),
});

type StatisticsFormValues = z.infer<typeof statisticsSchema>;

interface UpdateStatisticsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSubmit: (data: UpdateManualStatisticsInput) => Promise<void>;
  isLoading?: boolean;
  currentStats?: AccountStatistics | null;
}

const getDisplayedViewsValue = (stats?: AccountStatistics | null) =>
  stats ? stats.total_views || stats.total_impressions || 0 : 0;

export function UpdateStatisticsDialog({
  open,
  onOpenChange,
  onSubmit,
  isLoading,
  currentStats,
}: UpdateStatisticsDialogProps) {
  const t = useTranslations();

  const form = useForm<StatisticsFormValues>({
    resolver: zodResolver(statisticsSchema),
    defaultValues: {
      followers_count: currentStats?.followers_count ?? 0,
      following_count: currentStats?.following_count ?? 0,
      posts_count: currentStats?.posts_count ?? 0,
      total_reach: currentStats?.total_reach ?? 0,
      total_impressions: currentStats?.total_impressions ?? 0,
      total_views: getDisplayedViewsValue(currentStats),
      total_likes: currentStats?.total_likes ?? 0,
      total_comments: currentStats?.total_comments ?? 0,
      total_shares: currentStats?.total_shares ?? 0,
      engagement_rate: currentStats ? parseFloat(currentStats.engagement_rate) : 0,
      growth_rate: currentStats ? parseFloat(currentStats.growth_rate) : 0,
    },
  });

  // Reset form values when currentStats changes or dialog opens
  useEffect(() => {
    if (open && currentStats) {
      form.reset({
        followers_count: currentStats.followers_count,
        following_count: currentStats.following_count,
        posts_count: currentStats.posts_count,
        total_reach: currentStats.total_reach,
        total_impressions: currentStats.total_impressions,
        total_views: getDisplayedViewsValue(currentStats),
        total_likes: currentStats.total_likes,
        total_comments: currentStats.total_comments,
        total_shares: currentStats.total_shares,
        engagement_rate: parseFloat(currentStats.engagement_rate),
        growth_rate: parseFloat(currentStats.growth_rate),
      });
    }
  }, [open, currentStats, form]);

  const handleSubmit = async (values: StatisticsFormValues) => {
    await onSubmit(values);
    onOpenChange(false);
  };

  const handleClose = () => {
    form.reset();
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent layout="compact" className="sm:max-w-[480px]">
        <DialogHeader>
          <DialogTitle>{t("socialMedia.updateStatisticsTitle")}</DialogTitle>
        </DialogHeader>
        <DialogBody>
          
        </DialogBody>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <FormField
                control={form.control}
                name="followers_count"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.followers")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="following_count"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.followingField")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="posts_count"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.postsCountField")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="total_impressions"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.impressionsField")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="total_reach"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.reach")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="total_views"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.views")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="total_likes"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.totalLikesField")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="total_comments"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.totalCommentsField")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="total_shares"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.totalSharesField")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("socialMedia.enterNumber")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="engagement_rate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.engagementRate")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        step="0.01"
                        placeholder={t("socialMedia.enterRate")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="growth_rate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("socialMedia.growthRateField")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        step="0.01"
                        placeholder={t("socialMedia.enterRate")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <DialogFooter className="gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={handleClose}
                disabled={isLoading}
              >
                {t("common.cancel")}
              </Button>
              <AuthorizedAction
                action={{ actionKey: "social_media.update_manual_statistics" }}
                surface="form"
              >
                <Button type="submit" disabled={isLoading}>
                  {isLoading ? t("common.loading") : t("common.save")}
                </Button>
              </AuthorizedAction>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
