'use client'

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import { Loader2, Palette } from 'lucide-react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'

const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/

const formSchema = z.object({
  platform_name: z.string().min(1, 'Platform name is required'),
  primary_color: z.string().regex(hexColorRegex, 'Invalid hex color'),
  secondary_color: z.string().regex(hexColorRegex, 'Invalid hex color'),
  accent_color: z.string().regex(hexColorRegex, 'Invalid hex color'),
})

type FormValues = z.infer<typeof formSchema>

interface BrandingSettingsFormProps {
  settings: {
    platform_name?: string
    primary_color?: string
    secondary_color?: string
    accent_color?: string
  }
}

export function BrandingSettingsForm({ settings }: BrandingSettingsFormProps) {
  const utils = trpc.useUtils()

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      platform_name: settings.platform_name || 'Monaco Ocean Protection Challenge',
      primary_color: settings.primary_color || '#de0f1e',
      secondary_color: settings.secondary_color || '#053d57',
      accent_color: settings.accent_color || '#557f8c',
    },
  })

  const updateSettings = trpc.settings.updateMultiple.useMutation({
    onSuccess: () => {
      toast.success('Branding settings saved successfully')
      utils.settings.getByCategory.invalidate({ category: 'BRANDING' })
    },
    onError: (error) => {
      toast.error(`Failed to save settings: ${error.message}`)
    },
  })

  const onSubmit = (data: FormValues) => {
    updateSettings.mutate({
      settings: [
        { key: 'platform_name', value: data.platform_name },
        { key: 'primary_color', value: data.primary_color },
        { key: 'secondary_color', value: data.secondary_color },
        { key: 'accent_color', value: data.accent_color },
      ],
    })
  }

  const watchedColors = form.watch(['primary_color', 'secondary_color', 'accent_color'])

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="platform_name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Platform Name</FormLabel>
              <FormControl>
                <Input placeholder="Monaco Ocean Protection Challenge" {...field} />
              </FormControl>
              <FormDescription>
                The display name shown across the platform
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Color Preview */}
        <div className="rounded-lg border p-4">
          <p className="mb-3 text-sm font-medium">Color Preview</p>
          <div className="flex gap-4">
            <div className="flex flex-col items-center gap-2">
              <div
                className="h-12 w-12 rounded-lg border shadow-xs"
                style={{ backgroundColor: watchedColors[0] }}
              />
              <span className="text-xs text-muted-foreground">Primary</span>
            </div>
            <div className="flex flex-col items-center gap-2">
              <div
                className="h-12 w-12 rounded-lg border shadow-xs"
                style={{ backgroundColor: watchedColors[1] }}
              />
              <span className="text-xs text-muted-foreground">Secondary</span>
            </div>
            <div className="flex flex-col items-center gap-2">
              <div
                className="h-12 w-12 rounded-lg border shadow-xs"
                style={{ backgroundColor: watchedColors[2] }}
              />
              <span className="text-xs text-muted-foreground">Accent</span>
            </div>
          </div>
        </div>

        <FormField
          control={form.control}
          name="primary_color"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Primary Color</FormLabel>
              <div className="flex gap-2">
                <FormControl>
                  <Input type="color" className="h-10 w-14 cursor-pointer p-1" {...field} />
                </FormControl>
                <FormControl>
                  <Input
                    placeholder="#de0f1e"
                    {...field}
                    className="flex-1"
                  />
                </FormControl>
              </div>
              <FormDescription>
                Used for CTAs, alerts, and primary actions
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="secondary_color"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Secondary Color</FormLabel>
              <div className="flex gap-2">
                <FormControl>
                  <Input type="color" className="h-10 w-14 cursor-pointer p-1" {...field} />
                </FormControl>
                <FormControl>
                  <Input
                    placeholder="#053d57"
                    {...field}
                    className="flex-1"
                  />
                </FormControl>
              </div>
              <FormDescription>
                Used for headers and sidebar
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="accent_color"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Accent Color</FormLabel>
              <div className="flex gap-2">
                <FormControl>
                  <Input type="color" className="h-10 w-14 cursor-pointer p-1" {...field} />
                </FormControl>
                <FormControl>
                  <Input
                    placeholder="#557f8c"
                    {...field}
                    className="flex-1"
                  />
                </FormControl>
              </div>
              <FormDescription>
                Used for links and secondary elements
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <Button type="submit" disabled={updateSettings.isPending}>
          {updateSettings.isPending ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Saving...
            </>
          ) : (
            <>
              <Palette className="mr-2 h-4 w-4" />
              Save Branding Settings
            </>
          )}
        </Button>
      </form>
    </Form>
  )
}
