'use client';

import { useEffect, useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Heart, QrCode, MessageCircle, Send } from 'lucide-react';
import { API_BASE } from '@/lib/config';
import { apiFetch } from '@/lib/auth';
import { useT } from '@/i18n';

const ALIPAY_QR = process.env.NEXT_PUBLIC_DONATE_ALIPAY_QR || '';
const WECHAT_QR = process.env.NEXT_PUBLIC_DONATE_WECHAT_QR || '';

interface Donation {
  id: number;
  name: string | null;
  message: string | null;
  channel: string;
  amount: number | null;
  createdAt: string;
}

function channelLabel(t: ReturnType<typeof useT>, channel: string) {
  if (channel === 'WECHAT') return t.donate.wechat;
  return t.donate.alipay;
}

function QrCard({
  t,
  label,
  src,
}: {
  t: ReturnType<typeof useT>;
  label: string;
  src: string;
}) {
  return (
    <Card className="p-6 flex flex-col items-center text-center">
      <div className="w-12 h-12 bg-rose-100 dark:bg-rose-900/30 rounded-xl flex items-center justify-center mb-4">
        <QrCode className="w-6 h-6 text-rose-600 dark:text-rose-400" />
      </div>
      <h3 className="font-semibold text-foreground mb-1">{label}</h3>
      {src ? (
        <div className="mt-3 border border-border rounded-xl p-3 bg-white">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={src} alt={label} className="w-44 h-44 object-contain mx-auto" />
        </div>
      ) : (
        <p className="mt-3 text-sm text-muted-foreground">{t.donate.noQr}</p>
      )}
    </Card>
  );
}

export default function DonatePage() {
  const t = useT();
  const [donations, setDonations] = useState<Donation[]>([]);
  const [loading, setLoading] = useState(true);
  const [name, setName] = useState('');
  const [message, setMessage] = useState('');
  const [channel, setChannel] = useState<'ALIPAY' | 'WECHAT'>('ALIPAY');
  const [submitting, setSubmitting] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState(false);

  useEffect(() => {
    fetch(`${API_BASE}/donations`)
      .then((r) => r.json())
      .then((data) => setDonations(data.donations || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    setError(false);
    try {
      const res = await apiFetch(`${API_BASE}/donations`, {
        method: 'POST',
        body: JSON.stringify({
          name: name.trim() || undefined,
          message: message.trim() || undefined,
          channel,
        }),
      });
      if (res.ok) {
        setDone(true);
        setName('');
        setMessage('');
        const data = await res.json();
        if (data.donation) {
          setDonations((prev) => [data.donation, ...prev].slice(0, 20));
        }
      } else {
        setError(true);
      }
    } catch {
      setError(true);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="text-center mb-10">
        <div className="inline-flex w-14 h-14 bg-rose-100 dark:bg-rose-900/30 rounded-2xl items-center justify-center mb-4">
          <Heart className="w-7 h-7 text-rose-600 dark:text-rose-400" />
        </div>
        <h1 className="text-3xl font-bold text-foreground">{t.donate.title}</h1>
        <p className="mt-3 text-muted-foreground max-w-2xl mx-auto">{t.donate.desc}</p>
      </div>

      <Card className="p-8 mb-8 text-center bg-gradient-to-br from-rose-50 to-white dark:from-rose-950/20 dark:to-background">
        <h2 className="text-xl font-semibold text-foreground">{t.donate.supportTitle}</h2>
        <p className="mt-2 text-muted-foreground max-w-xl mx-auto">{t.donate.supportDesc}</p>
        <p className="mt-4 text-sm text-muted-foreground">{t.donate.qrNote}</p>
      </Card>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-10">
        <QrCard t={t} label={t.donate.alipay} src={ALIPAY_QR} />
        <QrCard t={t} label={t.donate.wechat} src={WECHAT_QR} />
      </div>

      <Card className="p-6 mb-10">
        <div className="flex items-center gap-2 mb-4">
          <MessageCircle className="w-5 h-5 text-brand-600 dark:text-brand-400" />
          <h2 className="text-lg font-semibold text-foreground">{t.donate.leaveMessage}</h2>
        </div>
        {done ? (
          <div className="text-center py-6">
            <p className="text-green-600 dark:text-green-400 font-medium">{t.donate.submitSuccess}</p>
            <Button variant="outline" className="mt-4" onClick={() => setDone(false)}>
              {t.donate.leaveMessage}
            </Button>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-4">
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t.donate.namePlaceholder}
              maxLength={40}
              className="w-full rounded-lg border border-border bg-background px-3 py-2 text-foreground outline-none focus:border-brand-500"
            />
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder={t.donate.messagePlaceholder}
              maxLength={280}
              rows={3}
              className="w-full rounded-lg border border-border bg-background px-3 py-2 text-foreground outline-none focus:border-brand-500 resize-none"
            />
            <div className="flex flex-wrap items-center gap-3">
              <span className="text-sm text-muted-foreground">{t.donate.channel}</span>
              <label className="flex items-center gap-1.5 text-sm cursor-pointer">
                <input
                  type="radio"
                  name="channel"
                  checked={channel === 'ALIPAY'}
                  onChange={() => setChannel('ALIPAY')}
                />
                {t.donate.alipay}
              </label>
              <label className="flex items-center gap-1.5 text-sm cursor-pointer">
                <input
                  type="radio"
                  name="channel"
                  checked={channel === 'WECHAT'}
                  onChange={() => setChannel('WECHAT')}
                />
                {t.donate.wechat}
              </label>
            </div>
            {error && <p className="text-sm text-red-600">{t.donate.submitFailed}</p>}
            <Button type="submit" disabled={submitting} className="gap-2">
              <Send className="w-4 h-4" />
              {submitting ? t.donate.submitting : t.donate.submit}
            </Button>
          </form>
        )}
      </Card>

      <div>
        <h2 className="text-xl font-semibold text-foreground mb-4">{t.donate.thanksWall}</h2>
        <p className="text-sm text-muted-foreground mb-4">{t.donate.thanksWallDesc}</p>
        {loading ? (
          <div className="space-y-3">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="h-16 w-full rounded-xl" />
            ))}
          </div>
        ) : donations.length === 0 ? (
          <Card className="p-8 text-center text-muted-foreground">{t.common.noData}</Card>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {donations.map((d) => (
              <Card key={d.id} className="p-4">
                <div className="flex items-center justify-between mb-1">
                  <span className="font-medium text-foreground">
                    {d.name || t.donate.anonymous}
                  </span>
                  <span className="text-xs text-muted-foreground">
                    {t.donate.via.replace('{channel}', channelLabel(t, d.channel))}
                  </span>
                </div>
                {d.message && (
                  <p className="text-sm text-muted-foreground">
                    {t.donate.says}：{d.message}
                  </p>
                )}
              </Card>
            ))}
          </div>
        )}
      </div>

      <p className="mt-10 text-xs text-muted-foreground text-center max-w-2xl mx-auto">
        {t.donate.disclaimer}
      </p>
    </div>
  );
}
