import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { queryKeys } from "@/hooks/queries/keys";
import { brandingService } from "@/services/branding.service";
import type { BrandingConfig } from "@/types";
import { toast } from "sonner";

const schema = z.object({
  primary_color: z.string(),
  secondary_color: z.string(),
  background_color: z.string(),
  custom_subdomain: z.string().optional(),
  login_title: z.string().optional(),
  login_description: z.string().optional(),
});

type FormValues = z.infer<typeof schema>;

export default function WhiteLabelBranding() {
  const { entityId: eid } = useParams<{ entityId: string }>();
  const entityId = Number(eid);
  const qc = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: queryKeys.branding.get(entityId),
    queryFn: () => brandingService.get(entityId),
    enabled: Number.isFinite(entityId),
  });

  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      primary_color: "#2563eb",
      secondary_color: "#64748b",
      background_color: "#f8fafc",
      custom_subdomain: "",
      login_title: "",
      login_description: "",
    },
  });

  useEffect(() => {
    if (data) {
      form.reset({
        primary_color: data.primary_color,
        secondary_color: data.secondary_color,
        background_color: data.background_color,
        custom_subdomain: data.custom_subdomain ?? "",
        login_title: data.login_title ?? "",
        login_description: data.login_description ?? "",
      });
    }
  }, [data, form]);

  const [logoUrl, setLogoUrl] = useState<string | undefined>(undefined);
  const [faviconUrl, setFaviconUrl] = useState<string | undefined>(undefined);

  useEffect(() => {
    setLogoUrl(data?.logo_url);
    setFaviconUrl(data?.favicon_url);
  }, [data?.logo_url, data?.favicon_url]);

  const saveMut = useMutation({
    mutationFn: async (values: FormValues) => {
      const payload: BrandingConfig = {
        ...values,
        logo_url: logoUrl,
        favicon_url: faviconUrl,
      };
      return brandingService.update(entityId, payload);
    },
    onSuccess: () => {
      toast.success("Branding saved.");
      qc.invalidateQueries({ queryKey: queryKeys.branding.get(entityId) });
    },
    onError: (e) => toast.error(e instanceof Error ? e.message : "Save failed"),
  });

  const resetMut = useMutation({
    mutationFn: () => brandingService.resetToDefault(entityId),
    onSuccess: () => {
      toast.success("Defaults restored.");
      qc.invalidateQueries({ queryKey: queryKeys.branding.get(entityId) });
    },
    onError: (e) => toast.error(e instanceof Error ? e.message : "Reset failed"),
  });

  const onLogo = (file: File | null) => {
    if (!file) return;
    brandingService.uploadLogo(entityId, file).then((r) => setLogoUrl(r.url)).catch((e) => toast.error(String(e)));
  };

  const onFavicon = (file: File | null) => {
    if (!file) return;
    brandingService
      .uploadFavicon(entityId, file)
      .then((r) => setFaviconUrl(r.url))
      .catch((e) => toast.error(String(e)));
  };

  const v = form.watch();

  if (!Number.isFinite(entityId)) {
    return <div className="p-6 text-destructive">Invalid entity.</div>;
  }

  if (isLoading && !data) {
    return <div className="p-6 text-muted-foreground">Loading branding…</div>;
  }

  return (
    <div className="space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">White-label branding</h1>
        <p className="text-muted-foreground text-sm mt-1">Entity #{entityId}</p>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Brand assets</CardTitle>
            <CardDescription>Logo, favicon, palette, and login copy</CardDescription>
          </CardHeader>
          <CardContent>
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit((vals) => saveMut.mutate(vals))}
                className="space-y-4"
              >
                <div className="space-y-2">
                  <FormLabel>Logo</FormLabel>
                  <Input type="file" accept="image/*" onChange={(e) => onLogo(e.target.files?.[0] ?? null)} />
                  {logoUrl ? (
                    <img src={logoUrl} alt="" className="h-12 object-contain" />
                  ) : null}
                </div>
                <div className="space-y-2">
                  <FormLabel>Favicon</FormLabel>
                  <Input type="file" accept="image/*" onChange={(e) => onFavicon(e.target.files?.[0] ?? null)} />
                  {faviconUrl ? (
                    <img src={faviconUrl} alt="" className="h-8 w-8 object-contain" />
                  ) : null}
                </div>
                <FormField
                  control={form.control}
                  name="primary_color"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Primary</FormLabel>
                      <div className="flex gap-2">
                        <FormControl>
                          <Input type="color" className="h-10 w-14 p-1" {...field} />
                        </FormControl>
                        <Input {...field} />
                      </div>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="secondary_color"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Secondary</FormLabel>
                      <div className="flex gap-2">
                        <FormControl>
                          <Input type="color" className="h-10 w-14 p-1" {...field} />
                        </FormControl>
                        <Input {...field} />
                      </div>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="background_color"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Background</FormLabel>
                      <div className="flex gap-2">
                        <FormControl>
                          <Input type="color" className="h-10 w-14 p-1" {...field} />
                        </FormControl>
                        <Input {...field} />
                      </div>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="custom_subdomain"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Subdomain</FormLabel>
                      <FormControl>
                        <Input placeholder="your-school" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="login_title"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Login title</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="login_description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Login description</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <div className="flex gap-2 pt-2">
                  <Button type="submit" disabled={saveMut.isPending}>
                    Save Branding
                  </Button>
                  <Button type="button" variant="outline" onClick={() => resetMut.mutate()} disabled={resetMut.isPending}>
                    Reset to Default
                  </Button>
                </div>
              </form>
            </Form>
          </CardContent>
        </Card>

        <Card className="lg:sticky lg:top-6 h-fit">
          <CardHeader>
            <CardTitle>Live preview</CardTitle>
            <CardDescription>Mock login with current colors</CardDescription>
          </CardHeader>
          <CardContent>
            <div
              className="rounded-xl border shadow-sm p-8 min-h-[320px] flex flex-col items-center justify-center gap-4"
              style={{ backgroundColor: v.background_color }}
            >
              {logoUrl ? <img src={logoUrl} alt="" className="h-10 object-contain" /> : null}
              <h2 className="text-xl font-semibold text-center" style={{ color: v.primary_color }}>
                {v.login_title || data?.entity_name || "Sign in"}
              </h2>
              <p className="text-sm text-center max-w-sm" style={{ color: v.secondary_color }}>
                {v.login_description || "Access your learning workspace."}
              </p>
              <div
                className="w-full max-w-xs space-y-3 rounded-lg border bg-background/80 p-4 backdrop-blur"
                style={{ borderColor: v.secondary_color }}
              >
                <Input placeholder="Email" disabled className="bg-background" />
                <Input type="password" placeholder="Password" disabled className="bg-background" />
                <Button className="w-full" style={{ backgroundColor: v.primary_color }}>
                  Continue
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
