/**
 * Label manager — create labels with colors, assign to mails.
 */

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Card } from '@/components/ui/Card';
import { EmptyState } from '@/components/ui/EmptyState';
import { useToast } from '@/components/ui/Toast';
import { ConfirmDialog } from '@/components/ui/ConfirmDialog';
import {
  fetchLabels,
  createLabel,
  deleteLabel,
  type MailLabel,
} from '@/api/mail';

const PRESET_COLORS = [
  '#ef4444', '#f59e0b', '#10b981', '#3b82f6',
  '#8b5cf6', '#ec4899', '#6366f1', '#64748b',
];

export function LabelManager() {
  const { t } = useTranslation();
  const toast = useToast();
  const [labels, setLabels] = useState<MailLabel[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [name, setName] = useState('');
  const [color, setColor] = useState(PRESET_COLORS[0]);
  const [saving, setSaving] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<MailLabel | null>(null);

  const load = useCallback(() => {
    setLoading(true);
    fetchLabels()
      .then((data) => {
        setLabels(data);
        setError(null);
      })
      .catch((err) => {
        setError(err instanceof Error ? err.message : String(err));
      })
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => { load(); }, [load]);

  const handleSave = useCallback(async () => {
    if (!name.trim()) return;
    setSaving(true);
    try {
      const label = await createLabel({ name, color });
      setLabels((prev) => [...prev, label]);
      toast.success(t('mail.labelCreated'));
      setShowForm(false);
      setName('');
      setColor(PRESET_COLORS[0]);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : String(err));
    } finally {
      setSaving(false);
    }
  }, [name, color, toast, t]);

  const handleDelete = useCallback(async () => {
    if (!deleteTarget) return;
    try {
      await deleteLabel(deleteTarget.id);
      setLabels((prev) => prev.filter((l) => l.id !== deleteTarget.id));
      toast.success(t('mail.labelDeleted'));
      setDeleteTarget(null);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : String(err));
    }
  }, [deleteTarget, toast, t]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-8" data-testid="label-manager-loading">
        <svg className="animate-spin h-5 w-5 text-secondary-400" fill="none" viewBox="0 0 24 24" aria-hidden="true">
          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
        </svg>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 bg-danger-50 border border-danger-200 rounded-md" role="alert" data-testid="label-manager-error">
        <p className="text-sm text-danger-700">{error}</p>
      </div>
    );
  }

  return (
    <div data-testid="label-manager">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-secondary-900">{t('mail.labels')}</h3>
        <Button size="sm" onClick={() => setShowForm(!showForm)} data-testid="new-label-btn">{t('mail.newLabel')}</Button>
      </div>

      {showForm && (
        <Card className="mb-4" data-testid="label-form">
          <div className="space-y-3">
            <Input
              label={t('mail.labelName')}
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t('mail.labelName')}
              required
            />
            <div>
              <label className="block text-sm font-medium text-secondary-700 mb-2">{t('mail.labelColor')}</label>
              <div className="flex flex-wrap gap-2" data-testid="label-color-picker">
                {PRESET_COLORS.map((c) => (
                  <button
                    key={c}
                    type="button"
                    onClick={() => setColor(c)}
                    className={`w-8 h-8 rounded-full ${color === c ? 'ring-2 ring-offset-2 ring-primary-500' : ''}`}
                    style={{ backgroundColor: c }}
                    aria-label={c}
                  />
                ))}
              </div>
            </div>
            <div className="flex gap-2">
              <Button onClick={handleSave} isLoading={saving} size="sm">{t('common.save')}</Button>
              <Button variant="secondary" size="sm" onClick={() => setShowForm(false)}>{t('common.cancel')}</Button>
            </div>
          </div>
        </Card>
      )}

      {labels.length === 0 && !showForm ? (
        <EmptyState title={t('mail.noLabels')} description={t('mail.noLabelsDesc')} />
      ) : (
        <div className="flex flex-wrap gap-2" data-testid="label-list">
          {labels.map((label) => (
            <div
              key={label.id}
              className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm"
              style={{ backgroundColor: label.color, color: '#fff' }}
            >
              <span>{label.name}</span>
              <button
                onClick={() => setDeleteTarget(label)}
                className="hover:opacity-70"
                aria-label={t('common.delete')}
                data-testid={`delete-label-${label.id}`}
                type="button"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          ))}
        </div>
      )}

      <ConfirmDialog
        open={!!deleteTarget}
        title={t('mail.deleteLabel')}
        message={t('mail.confirmDeleteLabel')}
        confirmLabel={t('common.delete')}
        variant="danger"
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}