"use client";

import { useState, useMemo } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Plus, Loader2, Pencil, CreditCard, CheckCircle, FlaskConical, Clock, SlidersHorizontal } from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate } from "@/shared/lib/format-date";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { useServerPagination } from "@/presentation/hooks/use-server-pagination";
import ServerDataTable from "@/presentation/components/shared/server-data-table";
import StatsCard from "@/presentation/components/shared/stats-card";
import { StatusBadge } from "@/presentation/components/shared/status-badge";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import { Badge } from "@/presentation/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/presentation/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/presentation/components/ui/tabs";
import { Switch } from "@/presentation/components/ui/switch";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from "@/presentation/components/ui/dialog";
import { SearchableSelect } from "@/presentation/components/ui/searchable-select";
import {
  Form, FormControl, FormField, FormItem, FormLabel, FormMessage,
} from "@/presentation/components/ui/form";
import { BillingTab } from "@/presentation/components/billing/billing-tab";
import { BillingProductsTab } from "@/presentation/components/billing/billing-products-tab";
import { DonnaTab } from "@/presentation/components/donna/donna-tab";
import { createPlanSchema, type CreatePlanFormValues } from "@/shared/schemas/subscription-plan.schema";
import type { Subscription } from "@/domain/entities/subscription";
import type { SubscriptionPlan } from "@/domain/entities/subscription-plan";
import type { Column } from "@/presentation/components/shared/server-data-table";
import { PlanEntitlementsDialog } from "@/presentation/components/entitlements/plan-entitlements-dialog";
import { UpsellSignalsTab } from "@/presentation/components/entitlements/upsell-signals-tab";

export default function SubscriptionsPage() {
  const t = useT();
  const locale = useLocale();
  usePageHeader(t.pages.subscriptions.title, t.pages.subscriptions.subtitle);
  const container = useRepositories();
  const pagination = useServerPagination();
  const [planDialogOpen, setPlanDialogOpen] = useState(false);
  const [editingPlan, setEditingPlan] = useState<SubscriptionPlan | null>(null);
  // SCRUM-353: the plan whose entitlements (modules, limits) are being edited
  const [entitlementsPlan, setEntitlementsPlan] = useState<SubscriptionPlan | null>(null);

  const { data: stats } = useApiQuery(
    () => container.subscriptionRepository.getStats(),
    { deps: [] }
  );

  const { data: subsResponse, loading: subsLoading, refetch: refetchSubs } = useApiQuery(
    () => container.subscriptionRepository.findAll(pagination.params),
    { deps: [pagination.params] }
  );

  const { data: plans, loading: plansLoading, refetch: refetchPlans } = useApiQuery(
    () => container.subscriptionRepository.getPlans(),
    { deps: [] }
  );

  const createPlanMutation = useApiMutation(
    (data: CreatePlanFormValues) => container.subscriptionRepository.createPlan(data),
    { successMessage: t.subscriptions.toasts.planCreated, onSuccess: () => { setPlanDialogOpen(false); refetchPlans(); } }
  );

  const updatePlanMutation = useApiMutation(
    ({ id, data }: { id: number; data: CreatePlanFormValues }) => container.subscriptionRepository.updatePlan(id, data),
    { successMessage: t.subscriptions.toasts.planUpdated, onSuccess: () => { setPlanDialogOpen(false); setEditingPlan(null); refetchPlans(); } }
  );

  const isEditingPlan = !!editingPlan;

  const schema = useMemo(() => createPlanSchema(t), [t]);
  const planForm = useForm<CreatePlanFormValues>({
    resolver: zodResolver(schema),
    defaultValues: { name: "", display_name: "", original_price: 0, billing_frequency: "monthly", is_active: true, is_popular: false, unlimited: false },
  });

  const openCreatePlan = () => {
    setEditingPlan(null);
    planForm.reset({ name: "", display_name: "", original_price: 0, billing_frequency: "monthly", is_active: true, is_popular: false, unlimited: false });
    setPlanDialogOpen(true);
  };

  const openEditPlan = (plan: SubscriptionPlan) => {
    setEditingPlan(plan);
    planForm.reset({
      name: plan.name,
      display_name: plan.display_name,
      description: plan.description ?? "",
      original_price: plan.original_price,
      discounted_price: plan.discounted_price ?? undefined,
      discount_percentage: plan.discount_percentage ?? undefined,
      billing_frequency: plan.billing_frequency,
      is_active: plan.is_active,
      is_popular: plan.is_popular,
      unlimited: plan.unlimited,
      display_order: plan.display_order ?? undefined as number | undefined,
    });
    setPlanDialogOpen(true);
  };

  const onPlanSubmit = async (values: CreatePlanFormValues) => {
    if (isEditingPlan && editingPlan) {
      await updatePlanMutation.mutate({ id: editingPlan.id, data: values });
    } else {
      await createPlanMutation.mutate(values);
    }
  };

  const subColumns: Column<Subscription>[] = [
    { key: "id", label: t.subscriptions.columns.id, sortable: true },
    { key: "company_name", label: t.forms.company },
    { key: "plan", label: t.subscriptions.columns.plan, render: (row) => row.plan?.name ?? "—" },
    { key: "status", label: t.forms.status, sortable: true, render: (row) => <StatusBadge status={row.status} /> },
    {
      key: "is_trial",
      label: t.subscriptions.columns.trial,
      render: (row) => row.is_trial ? (
        <Badge variant="outline" className="text-xs bg-blue-100 text-blue-800 border-blue-200">{t.common.yes}</Badge>
      ) : "—",
    },
    { key: "created_at", label: t.common.createdAt, sortable: true, render: (row) => formatDate(row.created_at, locale) },
  ];

  return (
    <div className="p-6 space-y-6">

      <Tabs defaultValue="subscriptions">
        <TabsList>
          <TabsTrigger value="subscriptions">{t.subscriptions.tabs.subscriptions}</TabsTrigger>
          <TabsTrigger value="plans">{t.subscriptions.tabs.plans}</TabsTrigger>
          <TabsTrigger value="billing">{t.subscriptions.tabs.billing}</TabsTrigger>
          <TabsTrigger value="products">{t.subscriptions.tabs.products}</TabsTrigger>
          <TabsTrigger value="signals">{t.subscriptions.tabs.signals}</TabsTrigger>
          <TabsTrigger value="donna">{t.subscriptions.tabs.donna}</TabsTrigger>
        </TabsList>

        <TabsContent value="subscriptions" className="mt-4 space-y-6">
          {stats && (
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
              <StatsCard title={t.subscriptions.stats.total} value={stats.total} icon={CreditCard} accent="blue" />
              <StatsCard title={t.subscriptions.stats.active} value={stats.active} icon={CheckCircle} accent="green" />
              <StatsCard title={t.subscriptions.stats.trial} value={stats.trial} icon={FlaskConical} accent="amber" />
              <StatsCard title={t.subscriptions.stats.expiredTrial} value={stats.expired_trial} icon={Clock} accent="red" />
            </div>
          )}
          <ServerDataTable
            columns={subColumns}
            data={subsResponse?.items ?? []}
            total={subsResponse?.total ?? 0}
            page={pagination.page}
            totalPages={subsResponse?.last_page ?? 1}
            loading={subsLoading}
            search={pagination.search}
            onSearchChange={pagination.setSearch}
            onPageChange={pagination.setPage}
            onSortChange={pagination.setSort}
            sortBy={pagination.orderBy}
            sortOrder={pagination.order}
            toolbar={
              <SearchableSelect
                label={t.subscriptions.trialFilter.label}
                triggerClassName="w-32"
                placeholder={t.subscriptions.trialFilter.label}
                value={(pagination.filters.is_trial as string) ?? "all"}
                onValueChange={(v) => pagination.setFilter("is_trial", v === "all" ? undefined : v)}
                options={[
                  { value: "all", label: t.common.all },
                  { value: "true", label: t.subscriptions.trialFilter.trial },
                  { value: "false", label: t.subscriptions.trialFilter.standard },
                ]}
              />
            }
          />
        </TabsContent>

        <TabsContent value="plans" className="mt-4 space-y-4">
          <div className="flex justify-end">
            <Button onClick={openCreatePlan} size="sm">
              <Plus className="w-4 h-4 mr-2" />
              {t.subscriptions.plans.newPlan}
            </Button>
          </div>
          {plansLoading ? (
            <div className="text-sm text-muted-foreground">{t.common.loading}</div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {(plans ?? []).map((plan) => (
                <Card key={plan.id} className="relative">
                  {plan.is_popular && (
                    <Badge className="absolute top-3 right-3 bg-blue-500 text-white">{t.subscriptions.plans.popular}</Badge>
                  )}
                  <CardHeader className="pb-2">
                    <CardTitle className="text-base">{plan.display_name}</CardTitle>
                    <p className="text-xs text-muted-foreground">{plan.name}</p>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div>
                      <span className="text-2xl font-bold">{plan.original_price}€</span>
                      <span className="text-sm text-muted-foreground">/{plan.billing_frequency === "monthly" ? t.subscriptions.plans.perMonth : t.subscriptions.plans.perYear}</span>
                      {plan.discounted_price != null && (
                        <span className="ml-2 text-sm text-emerald-600 font-medium">{plan.discounted_price}€</span>
                      )}
                    </div>
                    <div className="flex items-center gap-2 text-xs">
                      <Badge variant={plan.is_active ? "default" : "secondary"}>{plan.is_active ? t.common.active : t.common.inactive}</Badge>
                      {plan.unlimited && <Badge variant="outline">{t.subscriptions.plans.unlimited}</Badge>}
                      {plan.companies_count != null && <span className="text-muted-foreground">{t.subscriptions.plans.companiesCount(plan.companies_count)}</span>}
                    </div>
                    <Button variant="outline" size="sm" className="w-full" onClick={() => openEditPlan(plan)}>
                      <Pencil className="w-3 h-3 mr-2" />
                      {t.common.edit}
                    </Button>
                    <Button variant="outline" size="sm" className="w-full" onClick={() => setEntitlementsPlan(plan)}>
                      <SlidersHorizontal className="w-3 h-3 mr-2" />
                      {t.entitlements.planButton}
                    </Button>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </TabsContent>

        <TabsContent value="billing" className="mt-4">
          <BillingTab />
        </TabsContent>

        <TabsContent value="products" className="mt-4">
          <BillingProductsTab />
        </TabsContent>

        <TabsContent value="signals" className="mt-4">
          <UpsellSignalsTab />
        </TabsContent>

        <TabsContent value="donna" className="mt-4">
          <DonnaTab />
        </TabsContent>
      </Tabs>

      {/* Plan Create/Edit Dialog */}
      <Dialog open={planDialogOpen} onOpenChange={setPlanDialogOpen}>
        <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{isEditingPlan ? t.subscriptions.dialog.titleEdit : t.subscriptions.dialog.titleCreate}</DialogTitle>
          </DialogHeader>
          <Form {...planForm}>
            <form onSubmit={planForm.handleSubmit(onPlanSubmit)} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <FormField control={planForm.control} name="name" render={({ field }) => (
                  <FormItem><FormLabel>{t.subscriptions.dialog.identifier}</FormLabel><FormControl><Input {...field} /></FormControl><FormMessage /></FormItem>
                )} />
                <FormField control={planForm.control} name="display_name" render={({ field }) => (
                  <FormItem><FormLabel>{t.subscriptions.dialog.displayName}</FormLabel><FormControl><Input {...field} /></FormControl><FormMessage /></FormItem>
                )} />
              </div>
              <FormField control={planForm.control} name="description" render={({ field }) => (
                <FormItem><FormLabel>{t.forms.description}</FormLabel><FormControl><Input {...field} /></FormControl><FormMessage /></FormItem>
              )} />
              <div className="grid grid-cols-2 gap-4">
                <FormField control={planForm.control} name="original_price" render={({ field }) => (
                  <FormItem><FormLabel>{t.subscriptions.dialog.originalPrice}</FormLabel><FormControl><Input type="number" step="0.01" {...field} onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)} /></FormControl><FormMessage /></FormItem>
                )} />
                <FormField control={planForm.control} name="discounted_price" render={({ field }) => (
                  <FormItem><FormLabel>{t.subscriptions.dialog.discountedPrice}</FormLabel><FormControl><Input type="number" step="0.01" {...field} value={field.value ?? ""} onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : undefined)} /></FormControl><FormMessage /></FormItem>
                )} />
              </div>
              <FormField control={planForm.control} name="billing_frequency" render={({ field }) => (
                <FormItem>
                  <FormLabel>{t.subscriptions.dialog.frequency}</FormLabel>
                  <FormControl>
                    <SearchableSelect
                      triggerClassName="w-full h-10"
                      value={field.value}
                      onValueChange={field.onChange}
                      options={[
                        { value: "monthly", label: t.subscriptions.dialog.monthly },
                        { value: "yearly", label: t.subscriptions.dialog.yearly },
                      ]}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />
              <div className="flex items-center gap-6">
                <FormField control={planForm.control} name="is_active" render={({ field }) => (
                  <FormItem className="flex items-center gap-2 space-y-0">
                    <FormControl><Switch checked={field.value} onCheckedChange={field.onChange} /></FormControl>
                    <FormLabel className="!mt-0">{t.subscriptions.plans.activeField}</FormLabel>
                  </FormItem>
                )} />
                <FormField control={planForm.control} name="is_popular" render={({ field }) => (
                  <FormItem className="flex items-center gap-2 space-y-0">
                    <FormControl><Switch checked={field.value} onCheckedChange={field.onChange} /></FormControl>
                    <FormLabel className="!mt-0">{t.subscriptions.plans.popularField}</FormLabel>
                  </FormItem>
                )} />
                <FormField control={planForm.control} name="unlimited" render={({ field }) => (
                  <FormItem className="flex items-center gap-2 space-y-0">
                    <FormControl><Switch checked={field.value} onCheckedChange={field.onChange} /></FormControl>
                    <FormLabel className="!mt-0">{t.subscriptions.plans.unlimited}</FormLabel>
                  </FormItem>
                )} />
              </div>
              <div className="flex justify-end gap-2 pt-2">
                <Button type="button" variant="outline" onClick={() => setPlanDialogOpen(false)}>{t.common.cancel}</Button>
                <Button type="submit" disabled={createPlanMutation.loading || updatePlanMutation.loading}>
                  {(createPlanMutation.loading || updatePlanMutation.loading) && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                  {isEditingPlan ? t.common.save : t.common.create}
                </Button>
              </div>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      <PlanEntitlementsDialog
        planId={entitlementsPlan?.id ?? null}
        planName={entitlementsPlan?.display_name || entitlementsPlan?.name || ""}
        open={!!entitlementsPlan}
        onOpenChange={(open) => { if (!open) setEntitlementsPlan(null); }}
      />
    </div>
  );
}
