import React from 'react';
import { useTranslation } from 'react-i18next';
import { format } from 'date-fns';
import { de, enGB } from 'date-fns/locale';
import type { Locale } from 'date-fns';
import { Loader2, Palette, Plus, Power, Smile } from 'lucide-react';

import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';

import { AdminLayout } from '../components/AdminLayout';
import {
  getEmotions,
  createEmotion,
  updateEmotion,
  deleteEmotion,
  TenantEmotion,
  EmotionPayload,
} from '../api';
import { isAuthError } from '../auth/tokens';
import toast from 'react-hot-toast';

type EmotionFormState = {
  name: string;
  description: string;
  icon: string;
  color: string;
  is_active: boolean;
  sort_order: number;
};

const DEFAULT_COLOR = '#6366f1';
const INITIAL_FORM_STATE: EmotionFormState = {
  name: '',
  description: '',
  icon: 'lucide-smile',
  color: DEFAULT_COLOR,
  is_active: true,
  sort_order: 0,
};

export type EmotionsSectionProps = {
  embedded?: boolean;
};

export function EmotionsSection({ embedded = false }: EmotionsSectionProps) {
  const { t, i18n } = useTranslation('management');

  const [emotions, setEmotions] = React.useState<TenantEmotion[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [deleteTarget, setDeleteTarget] = React.useState<TenantEmotion | null>(null);
  const [saving, setSaving] = React.useState(false);
  const [form, setForm] = React.useState<EmotionFormState>(INITIAL_FORM_STATE);

  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      setLoading(true);
      setError(null);
      try {
        const data = await getEmotions();
        if (!cancelled) {
          setEmotions(data);
        }
      } catch (err) {
        if (!isAuthError(err)) {
          setError(t('emotions.errors.load'));
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }

    void load();

    return () => {
      cancelled = true;
    };
  }, [t]);

  const openCreateDialog = React.useCallback(() => {
    setForm(INITIAL_FORM_STATE);
    setDialogOpen(true);
  }, []);

  async function handleCreate(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!form.name.trim()) {
      setError(t('emotions.errors.nameRequired'));
      return;
    }

    setSaving(true);
    setError(null);
    const payload: EmotionPayload = {
      name: form.name.trim(),
      description: form.description.trim() || null,
      icon: form.icon.trim() || 'lucide-smile',
      color: form.color.trim() || DEFAULT_COLOR,
      is_active: form.is_active,
      sort_order: form.sort_order,
    };

    try {
      const created = await createEmotion(payload);
      setEmotions((prev) => [created, ...prev]);
      setDialogOpen(false);
      toast.success(t('emotions.toast.created', 'Emotion erstellt.'));
    } catch (err) {
      if (!isAuthError(err)) {
        setError(t('emotions.errors.create'));
        toast.error(t('emotions.toast.error', 'Emotion konnte nicht erstellt werden.'));
      }
    } finally {
      setSaving(false);
    }
  }

  async function toggleEmotion(emotion: TenantEmotion) {
    try {
      const updated = await updateEmotion(emotion.id, { is_active: !emotion.is_active });
      setEmotions((prev) => prev.map((item) => (item.id === updated.id ? updated : item)));
      toast.success(
        updated.is_active
          ? t('emotions.toast.activated', 'Emotion aktiviert.')
          : t('emotions.toast.deactivated', 'Emotion deaktiviert.')
      );
    } catch (err) {
      if (!isAuthError(err)) {
        setError(t('emotions.errors.toggle'));
        toast.error(t('emotions.toast.errorToggle', 'Emotion konnte nicht aktualisiert werden.'));
      }
    }
  }

  async function handleDeleteEmotion(emotion: TenantEmotion) {
    setSaving(true);
    try {
      await deleteEmotion(emotion.id);
      setEmotions((prev) => prev.filter((item) => item.id !== emotion.id));
      toast.success(t('emotions.toast.deleted', 'Emotion gelöscht.'));
    } catch (err) {
      if (!isAuthError(err)) {
        toast.error(t('emotions.toast.deleteError', 'Emotion konnte nicht gelöscht werden.'));
      }
    } finally {
      setSaving(false);
      setDeleteTarget(null);
    }
  }

  const locale = i18n.language.startsWith('en') ? enGB : de;
  const title = embedded ? t('emotions.title') : t('emotions.title');
  const subtitle = embedded
    ? t('emotions.subtitle')
    : t('emotions.subtitle');

  return (
    <div className="space-y-6">
      {error && (
        <Alert variant="destructive">
          <AlertTitle>{t('emotions.errors.genericTitle')}</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      <Card className="border-0 bg-white/85 shadow-xl shadow-pink-100/60">
        <CardHeader className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <CardTitle className="flex items-center gap-2 text-xl text-slate-900">
              <Palette className="h-5 w-5 text-pink-500" />
              {title}
            </CardTitle>
            <CardDescription className="text-sm text-slate-600">{subtitle}</CardDescription>
          </div>
          <Button
            className="bg-gradient-to-r from-pink-500 via-fuchsia-500 to-purple-500 text-white shadow-lg shadow-pink-500/20"
            onClick={openCreateDialog}
          >
            <Plus className="h-4 w-4" />
            {t('emotions.actions.create')}
          </Button>
        </CardHeader>
        <CardContent className="space-y-6">
          {loading ? (
            <EmotionSkeleton />
          ) : emotions.length === 0 ? (
            <EmptyEmotionsState onCreate={openCreateDialog} />
          ) : (
          <div className="grid gap-4 sm:grid-cols-2">
            {emotions.map((emotion) => (
              <EmotionCard
                key={emotion.id}
                emotion={emotion}
                onToggle={() => toggleEmotion(emotion)}
                onDelete={() => setDeleteTarget(emotion)}
                locale={locale}
              />
            ))}
          </div>
        )}
        </CardContent>
      </Card>

      <EmotionDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        form={form}
        setForm={setForm}
        saving={saving}
        onSubmit={handleCreate}
      />

      <Dialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t('emotions.delete.title', 'Emotion löschen?')}</DialogTitle>
          </DialogHeader>
          <p className="text-sm text-slate-600">
            {t('emotions.delete.confirm', { defaultValue: 'Soll "{{name}}" wirklich gelöscht werden?' , name: deleteTarget?.name ?? '' })}
          </p>
          <div className="mt-4 flex justify-end gap-2">
            <Button variant="outline" onClick={() => setDeleteTarget(null)}>
              {t('actions.cancel', 'Abbrechen')}
            </Button>
            <Button
              variant="destructive"
              onClick={() => deleteTarget && void handleDeleteEmotion(deleteTarget)}
              disabled={saving}
            >
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : t('actions.delete', 'Löschen')}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}

export default function EmotionsPage() {
  const { t } = useTranslation('management');
  return (
    <AdminLayout title={t('emotions.title')} subtitle={t('emotions.subtitle')}>
      <EmotionsSection />
    </AdminLayout>
  );
}

function EmotionCard({
  emotion,
  onToggle,
  onDelete,
  locale,
}: {
  emotion: TenantEmotion;
  onToggle: () => void;
  onDelete: () => void;
  locale: Locale;
}) {
  const { t } = useTranslation('management');
  const updated = emotion.updated_at ? format(new Date(emotion.updated_at), 'Pp', { locale }) : null;
  return (
    <Card className="border border-slate-200/70 bg-white/85 shadow-md shadow-pink-100/20">
      <CardHeader className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div
            className="flex h-9 w-9 items-center justify-center rounded-full"
            style={{ backgroundColor: `${emotion.color}20`, color: emotion.color ?? DEFAULT_COLOR }}
          >
            <Smile className="h-4 w-4" />
          </div>
          <div>
            <CardTitle className="text-base text-slate-900">{emotion.name}</CardTitle>
            {emotion.description ? (
              <CardDescription className="text-xs text-slate-500">{emotion.description}</CardDescription>
            ) : null}
          </div>
        </div>
        <Badge variant={emotion.is_active ? 'default' : 'secondary'}>
          {emotion.is_active ? t('emotions.status.active') : t('emotions.status.inactive')}
        </Badge>
      </CardHeader>
      <CardContent className="space-y-3 text-sm text-slate-600">
        <div className="flex flex-wrap gap-2">
          <Badge variant="outline">#{emotion.icon}</Badge>
          {emotion.event_types?.length ? (
            emotion.event_types.map((eventType) => (
              <Badge key={eventType.id} variant="outline">
                {eventType.name}
              </Badge>
            ))
          ) : (
            <Badge variant="outline">{t('emotions.labels.noEventType')}</Badge>
          )}
        </div>
        {updated ? <p className="text-xs text-slate-400">{t('emotions.labels.updated', { date: updated })}</p> : null}
      </CardContent>
      <CardFooter className="flex justify-between gap-2">
        <Button variant="ghost" onClick={onToggle} className="text-slate-500 hover:text-emerald-600">
          <Power className="mr-1 h-4 w-4" />
          {emotion.is_active ? t('emotions.actions.disable') : t('emotions.actions.enable')}
        </Button>
        {!emotion.is_global ? (
          <Button variant="ghost" size="sm" className="text-rose-600 hover:bg-rose-50" onClick={onDelete}>
            {t('actions.delete', 'Löschen')}
          </Button>
        ) : (
          <div className="h-8 w-8 rounded-full border border-slate-200" style={{ backgroundColor: emotion.color ?? DEFAULT_COLOR }} />
        )}
      </CardFooter>
    </Card>
  );
}

function EmotionDialog({
  open,
  onOpenChange,
  form,
  setForm,
  saving,
  onSubmit,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  form: EmotionFormState;
  setForm: React.Dispatch<React.SetStateAction<EmotionFormState>>;
  saving: boolean;
  onSubmit: (event: React.FormEvent<HTMLFormElement>) => void;
}) {
  const { t } = useTranslation('management');
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('emotions.dialogs.createTitle')}</DialogTitle>
        </DialogHeader>
        <form onSubmit={onSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="emotion-name">{t('emotions.dialogs.name')}</Label>
            <Input
              id="emotion-name"
              value={form.name}
              onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="emotion-description">{t('emotions.dialogs.description')}</Label>
            <Input
              id="emotion-description"
              value={form.description}
              onChange={(event) => setForm((prev) => ({ ...prev, description: event.target.value }))}
            />
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="emotion-icon">{t('emotions.dialogs.icon')}</Label>
              <Input
                id="emotion-icon"
                value={form.icon}
                onChange={(event) => setForm((prev) => ({ ...prev, icon: event.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="emotion-color">{t('emotions.dialogs.color')}</Label>
              <Input
                id="emotion-color"
                type="color"
                value={form.color}
                onChange={(event) => setForm((prev) => ({ ...prev, color: event.target.value }))}
              />
            </div>
          </div>
          <div className="flex items-center justify-between rounded-lg border border-slate-200 bg-slate-50/50 p-3">
            <div>
              <p className="text-sm font-medium text-slate-700">{t('emotions.dialogs.activeLabel')}</p>
              <p className="text-xs text-slate-500">{t('emotions.dialogs.activeDescription')}</p>
            </div>
            <Switch checked={form.is_active} onCheckedChange={(checked) => setForm((prev) => ({ ...prev, is_active: checked }))} />
          </div>
          <DialogFooter className="flex gap-2">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              {t('emotions.dialogs.cancel')}
            </Button>
            <Button type="submit" disabled={saving}>
              {saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
              {t('emotions.dialogs.submit')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

function EmotionSkeleton() {
  return (
    <div className="grid gap-4 sm:grid-cols-2">
      {Array.from({ length: 4 }).map((_, index) => (
        <div key={`emotion-skeleton-${index}`} className="h-36 animate-pulse rounded-xl bg-gradient-to-r from-white/40 via-white/60 to-white/40" />
      ))}
    </div>
  );
}

function EmptyEmotionsState({ onCreate }: { onCreate: () => void }) {
  const { t } = useTranslation('management');
  return (
    <div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-slate-200 bg-slate-50/60 p-10 text-center">
      <h3 className="text-base font-semibold text-slate-800">{t('emotions.empty.title')}</h3>
      <p className="text-sm text-slate-500">{t('emotions.empty.description')}</p>
      <Button onClick={onCreate} className="bg-gradient-to-r from-pink-500 via-fuchsia-500 to-purple-500 text-white">
        <Plus className="mr-1 h-4 w-4" />
        {t('emotions.actions.create')}
      </Button>
    </div>
  );
}
