import { useEffect } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useBrand, useCreateBrand, useUpdateBrand } from '@/hooks/useBrands';
import { useClients } from '@/hooks/useClients';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { ArrowLeft, Loader2 } from 'lucide-react';

const brandSchema = z.object({
  name: z.string().min(2, 'El nombre debe tener al menos 2 caracteres'),
  slug: z.string().optional(),
  client_id: z.string().min(1, 'Selecciona un cliente'),
  description: z.string().optional(),
  logo_url: z.string().url('URL inválida').optional().or(z.literal('')),
  primary_color: z.string().optional(),
  secondary_color: z.string().optional(),
  brand_voice: z.string().optional(),
  target_audience: z.string().optional(),
  keywords: z.string().optional(),
  is_active: z.boolean(),
});

type BrandFormData = z.infer<typeof brandSchema>;

export default function BrandFormPage() {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [searchParams] = useSearchParams();
  const preselectedClientId = searchParams.get('clientId');
  const isEditing = !!id;

  const { data: brand, isLoading: isLoadingBrand } = useBrand(id || '');
  const { data: clientsData, isLoading: isLoadingClients } = useClients({
    limit: 100,
  });
  const createBrand = useCreateBrand();
  const updateBrand = useUpdateBrand();

  const form = useForm<BrandFormData>({
    resolver: zodResolver(brandSchema),
    defaultValues: {
      name: '',
      slug: '',
      client_id: preselectedClientId || '',
      description: '',
      logo_url: '',
      primary_color: '#3B82F6',
      secondary_color: '#10B981',
      brand_voice: '',
      target_audience: '',
      keywords: '',
      is_active: true,
    },
  });

  useEffect(() => {
    if (brand) {
      form.reset({
        name: brand.name || '',
        slug: brand.slug || '',
        client_id: brand.client_id || '',
        description: brand.description || '',
        logo_url: brand.logo_url || '',
        primary_color: brand.primary_color || '#3B82F6',
        secondary_color: brand.secondary_color || '#10B981',
        brand_voice: brand.brand_voice || '',
        target_audience: brand.target_audience || '',
        keywords: Array.isArray(brand.keywords)
          ? brand.keywords.join(', ')
          : '',
        is_active: brand.is_active ?? true,
      });
    }
  }, [brand, form]);

  const onSubmit = async (data: BrandFormData) => {
    const cleanData = {
      ...data,
      logo_url: data.logo_url || undefined,
      keywords: data.keywords
        ? data.keywords.split(',').map((k) => k.trim())
        : undefined,
    };

    if (isEditing) {
      await updateBrand.mutateAsync({ id, data: cleanData });
    } else {
      await createBrand.mutateAsync(cleanData);
    }
    navigate('/crm/brands');
  };

  if (isEditing && isLoadingBrand) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={() => navigate(-1)}>
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div>
          <h1 className="text-3xl font-bold">
            {isEditing ? 'Editar Marca' : 'Nueva Marca'}
          </h1>
          <p className="text-muted-foreground">
            {isEditing
              ? 'Modifica los datos de la marca'
              : 'Completa los datos para crear una nueva marca'}
          </p>
        </div>
      </div>

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Información General</CardTitle>
              <CardDescription>Datos básicos de la marca</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <FormField
                  control={form.control}
                  name="client_id"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Cliente *</FormLabel>
                      <Select
                        onValueChange={field.onChange}
                        defaultValue={field.value}
                        disabled={isLoadingClients}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="Selecciona un cliente" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {clientsData?.data?.map((client) => (
                            <SelectItem key={client.id} value={client.id}>
                              {client.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Nombre *</FormLabel>
                      <FormControl>
                        <Input placeholder="Nombre de la marca" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="slug"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Slug</FormLabel>
                      <FormControl>
                        <Input placeholder="marca-slug" {...field} />
                      </FormControl>
                      <FormDescription>
                        Se genera automáticamente si se deja vacío
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="logo_url"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>URL del Logo</FormLabel>
                      <FormControl>
                        <Input
                          type="url"
                          placeholder="https://ejemplo.com/logo.png"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Descripción</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Descripción de la marca..."
                        className="min-h-[80px]"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Identidad Visual</CardTitle>
              <CardDescription>Colores de la marca</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <FormField
                  control={form.control}
                  name="primary_color"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Color Primario</FormLabel>
                      <div className="flex gap-2">
                        <FormControl>
                          <Input type="color" className="w-14 h-10" {...field} />
                        </FormControl>
                        <Input
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="#3B82F6"
                          className="flex-1"
                        />
                      </div>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="secondary_color"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Color Secundario</FormLabel>
                      <div className="flex gap-2">
                        <FormControl>
                          <Input type="color" className="w-14 h-10" {...field} />
                        </FormControl>
                        <Input
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="#10B981"
                          className="flex-1"
                        />
                      </div>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Voz y Audiencia</CardTitle>
              <CardDescription>
                Define cómo se comunica la marca y a quién va dirigida
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <FormField
                control={form.control}
                name="brand_voice"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Voz de Marca</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Describe el tono y estilo de comunicación de la marca..."
                        className="min-h-[80px]"
                        {...field}
                      />
                    </FormControl>
                    <FormDescription>
                      Ej: Profesional pero cercano, innovador, confiable
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="target_audience"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Audiencia Objetivo</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Describe el público objetivo de la marca..."
                        className="min-h-[80px]"
                        {...field}
                      />
                    </FormControl>
                    <FormDescription>
                      Ej: Profesionales de 25-45 años interesados en tecnología
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="keywords"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Palabras Clave</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="innovación, calidad, tecnología"
                        {...field}
                      />
                    </FormControl>
                    <FormDescription>
                      Separadas por comas, se usarán para generación de contenido
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Configuración</CardTitle>
            </CardHeader>
            <CardContent>
              <FormField
                control={form.control}
                name="is_active"
                render={({ field }) => (
                  <FormItem className="flex items-center justify-between rounded-lg border p-4">
                    <div className="space-y-0.5">
                      <FormLabel className="text-base">Marca Activa</FormLabel>
                      <FormDescription>
                        Las marcas inactivas no aparecen en las listas de
                        selección
                      </FormDescription>
                    </div>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />
            </CardContent>
          </Card>

          <div className="flex justify-end gap-4">
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate('/crm/brands')}
            >
              Cancelar
            </Button>
            <Button
              type="submit"
              disabled={createBrand.isPending || updateBrand.isPending}
            >
              {(createBrand.isPending || updateBrand.isPending) && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              {isEditing ? 'Guardar Cambios' : 'Crear Marca'}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
