"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

import { SettingsPageLayout } from "@/components/dashboard/settings/settings-page-layout";
import {
  SettingsSubnavCard,
  type SettingsSubnavItem,
} from "@/components/dashboard/settings/settings-subnav-card";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import type {
  AdminFontItem,
  AdminSiteFontSettings,
  AdminTrackingSettings,
} from "@/components/dashboard/settings/settings-api-types";
import { SettingsConfirmDialog } from "@/components/dashboard/settings/settings-confirm-dialog";
import { Pencil, Plus, Trash2 } from "lucide-react";
import { useTranslations } from "next-intl";

interface SiteSettingsViewProps {
  activeTab: "fonts" | "seo";
  fonts: AdminFontItem[];
  siteFontSettings?: AdminSiteFontSettings | null;
  trackingSettings?: AdminTrackingSettings | null;
  isEditFontOpen: boolean;
  isDeleteFontOpen: boolean;
  isAddFontOpen: boolean;
  fontName: string;
  fontFamily: string;
  fontUrl: string;
  fontSource: string;
  fontWeights: string;
  fontOrder: number;
  selectedFontId: string | null;
  primaryFontId: string;
  secondaryFontId: string;
  tertiaryFontId: string;
  seoForm: Partial<AdminTrackingSettings>;
  onOpenEditFont: (fontId: string) => void;
  onOpenAddFont: () => void;
  onOpenDeleteFont: (fontId: string) => void;
  onEditFontOpenChange: (open: boolean) => void;
  onAddFontOpenChange: (open: boolean) => void;
  onDeleteFontOpenChange: (open: boolean) => void;
  onChangeFontName: (value: string) => void;
  onChangeFontFamily: (value: string) => void;
  onChangeFontUrl: (value: string) => void;
  onChangeFontSource: (value: string) => void;
  onChangeFontWeights: (value: string) => void;
  onChangeFontOrder: (value: number) => void;
  onChangePrimaryFontId: (value: string) => void;
  onChangeSecondaryFontId: (value: string) => void;
  onChangeTertiaryFontId: (value: string) => void;
  onChangeSeoForm: (value: Partial<AdminTrackingSettings>) => void;
  onSaveFontEdit: () => Promise<void>;
  onSaveNewFont: () => Promise<void>;
  onConfirmDeleteFont: () => Promise<void>;
  onSaveSiteFontSettings: () => Promise<void>;
  onSaveSeoSettings: () => Promise<void>;
  onGenerateSitemap: () => Promise<void>;
  isLoadingFonts: boolean;
  isLoadingSiteFonts: boolean;
  isLoadingTrackingSettings: boolean;
  isSavingSettings: boolean;
}

export function SiteSettingsView({
  activeTab,
  fonts,
  siteFontSettings,
  trackingSettings,
  isEditFontOpen,
  isDeleteFontOpen,
  isAddFontOpen,
  fontName,
  fontFamily,
  fontUrl,
  fontSource,
  fontWeights,
  fontOrder,
  selectedFontId,
  primaryFontId,
  secondaryFontId,
  tertiaryFontId,
  seoForm,
  onOpenEditFont,
  onOpenAddFont,
  onOpenDeleteFont,
  onEditFontOpenChange,
  onAddFontOpenChange,
  onDeleteFontOpenChange,
  onChangeFontName,
  onChangeFontFamily,
  onChangeFontUrl,
  onChangeFontSource,
  onChangeFontWeights,
  onChangeFontOrder,
  onChangePrimaryFontId,
  onChangeSecondaryFontId,
  onChangeTertiaryFontId,
  onChangeSeoForm,
  onSaveFontEdit,
  onSaveNewFont,
  onConfirmDeleteFont,
  onSaveSiteFontSettings,
  onSaveSeoSettings,
  onGenerateSitemap,
  isLoadingFonts,
  isLoadingSiteFonts,
  isLoadingTrackingSettings,
  isSavingSettings,
}: SiteSettingsViewProps) {
  const t = useTranslations("dashboard.settings");
  const router = useRouter();

  const tabItems: SettingsSubnavItem[] = [
    { id: "fonts", label: t("site.tabs.fonts"), href: "/dashboard/settings/site?tab=fonts" },
    { id: "seo", label: t("site.tabs.seo"), href: "/dashboard/settings/site?tab=seo" },
    { id: "company", label: t("site.tabs.companyData"), href: "/dashboard/settings/company" },
  ];

  const activeFonts = fonts.filter(f => f.is_active);

  if (activeTab === "fonts") {
    return (
      <>
        <SettingsPageLayout
          sideContent={<SettingsSubnavCard items={tabItems} activeId="fonts" />}
        >
          <section className="space-y-4">
            <div className="rounded-2xl border border-border bg-card p-6">
              <h2 className="mb-5 text-xl font-bold text-foreground">
                {t("site.fonts.title")}
              </h2>

              {isLoadingSiteFonts ? (
                <div className="py-8 text-center text-muted-foreground">Loading...</div>
              ) : (
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label>{t("site.fonts.primaryFont")}</Label>
                    <Select
                      value={primaryFontId}
                      onValueChange={onChangePrimaryFontId}
                    >
                      <SelectTrigger className="h-12 rounded-xl">
                        <SelectValue placeholder={t("form.placeholders.select")} />
                      </SelectTrigger>
                      <SelectContent>
                        {activeFonts.map((font) => (
                          <SelectItem key={font.id} value={font.id.toString()}>
                            {font.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label>{t("site.fonts.secondaryFont")}</Label>
                    <Select
                      value={secondaryFontId}
                      onValueChange={onChangeSecondaryFontId}
                    >
                      <SelectTrigger className="h-12 rounded-xl">
                        <SelectValue placeholder={t("form.placeholders.select")} />
                      </SelectTrigger>
                      <SelectContent>
                        {activeFonts.map((font) => (
                          <SelectItem key={font.id} value={font.id.toString()}>
                            {font.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label>{t("site.fonts.tertiaryFont")}</Label>
                    <Select
                      value={tertiaryFontId}
                      onValueChange={onChangeTertiaryFontId}
                    >
                      <SelectTrigger className="h-12 rounded-xl">
                        <SelectValue placeholder={t("form.placeholders.select")} />
                      </SelectTrigger>
                      <SelectContent>
                        {activeFonts.map((font) => (
                          <SelectItem key={font.id} value={font.id.toString()}>
                            {font.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <Button
                    type="button"
                    className="mt-6 h-12 rounded-xl px-8"
                    onClick={onSaveSiteFontSettings}
                    disabled={isSavingSettings}
                  >
                    {isSavingSettings ? t("actions.saving") : t("actions.saveChanges")}
                  </Button>
                </div>
              )}
            </div>

            <section className="overflow-hidden rounded-2xl border border-border bg-card">
              <div className="flex items-center justify-between border-b border-border p-6">
                <h3 className="text-base font-bold text-foreground">
                  {t("site.fonts.tableTitle")}
                </h3>
                <Button type="button" className="h-11 rounded-xl px-4" onClick={onOpenAddFont}>
                  <Plus className="size-4" />
                  <span>{t("actions.addNew")}</span>
                </Button>
              </div>

              <div className="overflow-x-auto">
                {isLoadingFonts ? (
                  <div className="py-8 text-center text-muted-foreground">Loading...</div>
                ) : (
                  <Table className="min-w-[760px]">
                    <TableHeader>
                      <TableRow className="bg-highlights-bg hover:bg-highlights-bg">
                        <TableHead className="h-12 w-14 text-center">#</TableHead>
                        <TableHead className="h-12 text-center">
                          {t("site.fonts.table.name")}
                        </TableHead>
                        <TableHead className="h-12 text-center">
                          {t("site.fonts.table.family")}
                        </TableHead>
                        <TableHead className="h-12 text-center">
                          {t("site.fonts.table.source")}
                        </TableHead>
                        <TableHead className="h-12 w-[120px] text-center">
                          {t("site.fonts.table.settings")}
                        </TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {fonts.map((font, index) => (
                        <TableRow key={font.id} className="h-[72px]">
                          <TableCell className="text-center">{index + 1}</TableCell>
                          <TableCell className="text-center font-medium text-foreground">
                            {font.name}
                          </TableCell>
                          <TableCell className="text-center text-sm text-muted-foreground">
                            {font.font_family}
                          </TableCell>
                          <TableCell className="text-center text-sm text-muted-foreground">
                            {font.source}
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center justify-center gap-2">
                              <Button
                                variant="ghost"
                                size="icon"
                                onClick={() => onOpenEditFont(font.id.toString())}
                                className="h-8 w-8 rounded-[10px]"
                              >
                                <Pencil className="size-4" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="icon"
                                onClick={() => onOpenDeleteFont(font.id.toString())}
                                className="h-8 w-8 rounded-[10px] text-red-500 hover:text-red-600"
                              >
                                <Trash2 className="size-4" />
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                )}
              </div>
            </section>
          </section>
        </SettingsPageLayout>

        {/* Edit Font Dialog */}
        <Dialog open={isEditFontOpen} onOpenChange={onEditFontOpenChange}>
          <DialogContent className="max-w-[680px] rounded-2xl p-8">
            <DialogHeader>
              <DialogTitle className="text-2xl font-bold text-foreground">
                {t("site.fonts.editTitle")}
              </DialogTitle>
            </DialogHeader>

            <div className="grid gap-4">
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.name")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={fontName}
                  onChange={(e) => onChangeFontName(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.family")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={fontFamily}
                  onChange={(e) => onChangeFontFamily(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.source")}</Label>
                <Select value={fontSource} onValueChange={onChangeFontSource}>
                  <SelectTrigger className="h-12 rounded-xl">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="google">Google Fonts</SelectItem>
                    <SelectItem value="local">Local</SelectItem>
                    <SelectItem value="custom">Custom</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.url")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={fontUrl}
                  onChange={(e) => onChangeFontUrl(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.weights")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={fontWeights}
                  onChange={(e) => onChangeFontWeights(e.target.value)}
                  placeholder="400,500,700"
                />
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.order")}</Label>
                <Input
                  type="number"
                  className="h-12 rounded-xl"
                  value={fontOrder}
                  onChange={(e) => onChangeFontOrder(Number(e.target.value))}
                />
              </div>
            </div>

            <DialogFooter className="flex-row justify-start gap-3 sm:justify-start">
              <Button
                type="button"
                variant="outline"
                onClick={() => onEditFontOpenChange(false)}
              >
                {t("actions.cancel")}
              </Button>
              <Button type="button" onClick={onSaveFontEdit} disabled={isSavingSettings}>
                {isSavingSettings ? t("actions.saving") : t("actions.saveEdit")}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Add Font Dialog */}
        <Dialog open={isAddFontOpen} onOpenChange={onAddFontOpenChange}>
          <DialogContent className="max-w-[680px] rounded-2xl p-8">
            <DialogHeader>
              <DialogTitle className="text-2xl font-bold text-foreground">
                {t("site.fonts.addTitle")}
              </DialogTitle>
            </DialogHeader>

            <div className="grid gap-4">
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.name")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={fontName}
                  onChange={(e) => onChangeFontName(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.family")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={fontFamily}
                  onChange={(e) => onChangeFontFamily(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.source")}</Label>
                <Select value={fontSource} onValueChange={onChangeFontSource}>
                  <SelectTrigger className="h-12 rounded-xl">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="google">Google Fonts</SelectItem>
                    <SelectItem value="local">Local</SelectItem>
                    <SelectItem value="custom">Custom</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.url")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={fontUrl}
                  onChange={(e) => onChangeFontUrl(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.weights")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={fontWeights}
                  onChange={(e) => onChangeFontWeights(e.target.value)}
                  placeholder="400,500,700"
                />
              </div>
              <div className="space-y-2">
                <Label>{t("site.fonts.fields.order")}</Label>
                <Input
                  type="number"
                  className="h-12 rounded-xl"
                  value={fontOrder}
                  onChange={(e) => onChangeFontOrder(Number(e.target.value))}
                />
              </div>
            </div>

            <DialogFooter className="flex-row justify-start gap-3 sm:justify-start">
              <Button
                type="button"
                variant="outline"
                onClick={() => onAddFontOpenChange(false)}
              >
                {t("actions.cancel")}
              </Button>
              <Button type="button" onClick={onSaveNewFont} disabled={isSavingSettings}>
                {isSavingSettings ? t("actions.saving") : t("actions.add")}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Delete Confirmation Dialog */}
        <SettingsConfirmDialog
          open={isDeleteFontOpen}
          onOpenChange={onDeleteFontOpenChange}
          title={t("site.fonts.delete.title")}
          description={t("site.fonts.delete.description")}
          cancelLabel={t("actions.back")}
          confirmLabel={t("actions.confirmDelete")}
          destructive
          onConfirm={onConfirmDeleteFont}
        />
      </>
    );
  } else {
    return (
      <SettingsPageLayout
        sideContent={<SettingsSubnavCard items={tabItems} activeId="seo" />}
      >
        <section className="rounded-2xl border border-border bg-card p-6">
          {isLoadingTrackingSettings ? (
            <div className="py-8 text-center text-muted-foreground">Loading...</div>
          ) : (
            <>
              <h2 className="mb-5 text-xl font-bold text-foreground">{t("site.seo.title")}</h2>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label>{t("site.seo.siteTitle")}</Label>
                  <Input
                    className="h-12 rounded-xl"
                    value={seoForm.site_title || ""}
                    onChange={(e) => onChangeSeoForm({ ...seoForm, site_title: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <Label>{t("site.seo.seoKeywords")}</Label>
                  <Input
                    className="h-12 rounded-xl"
                    value={seoForm.seo_keywords || ""}
                    onChange={(e) => onChangeSeoForm({ ...seoForm, seo_keywords: e.target.value })}
                  />
                </div>

                <div className="space-y-2">
                  <Label>{t("site.seo.gaEnabled")}</Label>
                  <Select
                    value={seoForm.ga_enabled ? "true" : "false"}
                    onValueChange={(v) => onChangeSeoForm({ ...seoForm, ga_enabled: v === "true" })}
                  >
                    <SelectTrigger className="h-12 rounded-xl">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="true">{t("filters.status.active")}</SelectItem>
                      <SelectItem value="false">{t("filters.status.inactive")}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>{t("site.seo.gaPropertyId")}</Label>
                  <Input
                    className="h-12 rounded-xl"
                    value={seoForm.ga_property_id || ""}
                    onChange={(e) => onChangeSeoForm({ ...seoForm, ga_property_id: e.target.value })}
                  />
                </div>

                <div className="space-y-2">
                  <Label>{t("site.seo.googleTagId")}</Label>
                  <Input
                    className="h-12 rounded-xl"
                    value={seoForm.google_tag_id || ""}
                    onChange={(e) => onChangeSeoForm({ ...seoForm, google_tag_id: e.target.value })}
                  />
                </div>
              </div>

              <div className="mt-4 space-y-2">
                <Label>{t("site.seo.seoDescription")}</Label>
                <Textarea
                  className="min-h-[96px] rounded-xl"
                  value={seoForm.seo_description || ""}
                  onChange={(e) => onChangeSeoForm({ ...seoForm, seo_description: e.target.value })}
                />
              </div>

              <div className="mt-4 space-y-2">
                <Label>{t("site.seo.ogTitle")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={seoForm.og_title || ""}
                  onChange={(e) => onChangeSeoForm({ ...seoForm, og_title: e.target.value })}
                />
              </div>

              <div className="mt-4 space-y-2">
                <Label>{t("site.seo.ogDescription")}</Label>
                <Textarea
                  className="min-h-[96px] rounded-xl"
                  value={seoForm.og_description || ""}
                  onChange={(e) => onChangeSeoForm({ ...seoForm, og_description: e.target.value })}
                />
              </div>

              <div className="mt-4 space-y-2">
                <Label>{t("site.seo.ogImage")}</Label>
                <Input
                  className="h-12 rounded-xl"
                  value={seoForm.og_image || ""}
                  onChange={(e) => onChangeSeoForm({ ...seoForm, og_image: e.target.value })}
                />
              </div>

              <div className="mt-6 flex gap-3">
                <Button
                  type="button"
                  className="h-12 rounded-xl px-8"
                  onClick={onSaveSeoSettings}
                  disabled={isSavingSettings}
                >
                  {isSavingSettings ? t("actions.saving") : t("actions.save")}
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  className="h-12 rounded-xl px-8"
                  onClick={onGenerateSitemap}
                >
                  {t("site.seo.generateSitemap")}
                </Button>
              </div>
            </>
          )}
        </section>
      </SettingsPageLayout>
    );
  }
}
