'use client';

import { useState, useEffect, useCallback } from 'react';
import { subscriptionService as subscriptionSettingsService, type SubscriptionSettings, type UpdateSubscriptionSettingsDto } from '@/services/subscription.service';
import { subscriptionService, type Subscription, type SubscriptionStatus } from '@/services/subscription.service';
import { getErrorMessage } from '@/lib/errors';
import { cn } from '@/lib/utils';
import { useSystemConfig } from '@/hooks/useSystemConfig';
import { TableSkeleton } from '@/components/priority/skeletons';
import EmptyState from '@/components/EmptyState';
import {
  Settings, Save, RefreshCw, DollarSign, Wallet, Network, Clock, ToggleLeft, ToggleRight,
  Search, X,
} from 'lucide-react';

const SUB_STATUS_COLORS: Record<string, string> = {
  ACTIVE: 'bg-emerald-500/20 text-emerald-300',
  EXPIRED: 'bg-slate-500/20 text-slate-300',
  TERMINATED: 'bg-red-500/20 text-red-300',
  GRACE: 'bg-amber-500/20 text-amber-300',
  CANCELLED: 'bg-red-500/20 text-red-300',
};

export default function SuperAdminSubscriptionSettingsPage() {
  const sysConfig = useSystemConfig();
  const [settings, setSettings] = useState<SubscriptionSettings | null>(null);
  const [local, setLocal] = useState<SubscriptionSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
  const [subLoading, setSubLoading] = useState(true);
  const [subStatusFilter, setSubStatusFilter] = useState<SubscriptionStatus | 'ALL'>('ALL');
  const [subSearch, setSubSearch] = useState('');
  const [subPage, setSubPage] = useState(1);
  const subLimit = 15;
  const [subMeta, setSubMeta] = useState<{ total: number; limit: number; offset: number } | null>(null);

  const loadSettings = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await subscriptionSettingsService.getSubscriptionSettings();
      setSettings(data);
      setLocal(data);
    } catch (err: any) {
      setError(err?.message || 'Failed to load subscription settings');
    } finally {
      setLoading(false);
    }
  }, []);

  const loadSubscriptions = useCallback(async () => {
    setSubLoading(true);
    try {
      const res = await subscriptionService.listUserSubscriptions({
        status: subStatusFilter === 'ALL' ? undefined : subStatusFilter,
        page: subPage,
        limit: subLimit,
      });
      setSubscriptions(res.data || []);
      setSubMeta(res.meta || null);
    } catch {
      setSubscriptions([]);
      setSubMeta(null);
    } finally {
      setSubLoading(false);
    }
  }, [subStatusFilter, subPage]);

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

  useEffect(() => {
    setSubPage(1);
  }, [subStatusFilter]);

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

  const updateField = <K extends keyof UpdateSubscriptionSettingsDto>(key: K, value: UpdateSubscriptionSettingsDto[K]) => {
    setLocal((prev) => (prev ? { ...prev, [key]: value } : prev));
  };

  const handlePaymentField = (key: 'walletAddress' | 'network' | 'currency', value: string) => {
    setLocal((prev) =>
      prev
        ? {
            ...prev,
            paymentDetails: { ...prev.paymentDetails, [key]: value },
          }
        : prev,
    );
  };

  const handleSave = async () => {
    if (!local) return;
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      const payload: UpdateSubscriptionSettingsDto = {
        fee: local.fee ? parseFloat(local.fee) : undefined,
        currency: local.paymentDetails?.currency || local.currency,
        durationDays: local.durationDays,
        gracePeriodDays: local.gracePeriodDays,
        renewalEnabled: local.renewalEnabled,
        walletAddress: local.paymentDetails?.walletAddress,
        network: local.paymentDetails?.network || '',
        applyToExistingUsers: local.applyToExistingUsers,
      };
      await subscriptionSettingsService.updateSubscriptionSettings(payload);

      // Also create or update a subscription plan from these settings
      if (local.fee && local.durationDays) {
        try {
          await subscriptionService.createSubscriptionPlan({
            name: 'Default Subscription',
            description: `Auto-created from subscription settings. Duration: ${local.durationDays} days`,
            price: local.fee.toString(),
            currency: local.paymentDetails?.currency || local.currency || 'USDT',
            durationDays: local.durationDays,
            gracePeriodDays: local.gracePeriodDays,
            isActive: true,
          });
        } catch (planErr: any) {
          // Plan might already exist, which is fine
          if (!planErr?.message?.includes('Unique constraint')) {
            console.warn(`Could not auto-create plan: ${planErr?.message}`);
          }
        }
      }

      setSuccess('Subscription settings saved successfully');
      loadSettings();
    } catch (err: any) {
      setError(err?.message || 'Failed to update settings');
    } finally {
      setSaving(false);
    }
  };

  const filteredSubs = subscriptions ? subscriptions.filter((s) => {
    if (!subSearch) return true;
    const q = subSearch.toLowerCase();
    return (
      (s.userId || '').toLowerCase().includes(q) ||
      (s.plan?.name || '').toLowerCase().includes(q) ||
      (s.planId || '').toLowerCase().includes(q)
    );
  }) : [];

  const paymentDetails = local?.paymentDetails ?? ({} as SubscriptionSettings['paymentDetails']);

  if (loading) return <TableSkeleton rows={5} />;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Subscription Settings</h1>
          <p className="text-sm text-slate-400">Configure subscription fees, duration, payment details, and view user subscriptions.</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={loadSettings} className="rounded-lg border border-white/10 p-2 text-slate-300 hover:bg-white/5">
            <RefreshCw className={cn('h-5 w-5', loading && 'animate-spin')} />
          </button>
        </div>
      </div>

      {error && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400 flex items-center justify-between">
          <span>{error}</span>
          <button onClick={() => setError(null)} className="text-red-300 hover:text-white">&times;</button>
        </div>
      )}
      {success && (
        <div className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-400 flex items-center justify-between">
          <span>{success}</span>
          <button onClick={() => setSuccess(null)} className="text-emerald-300 hover:text-white">&times;</button>
        </div>
      )}

      {local && (
        <div className="rounded-xl border border-white/10 bg-slate-900/50">
          <div className="flex items-center justify-between border-b border-white/10 p-5">
            <div className="flex items-center gap-3">
              <div className="rounded-lg bg-blue-500/10 p-2">
                <Settings className="h-5 w-5 text-blue-400" />
              </div>
              <div>
                <h2 className="text-lg font-semibold text-white">Subscription Configuration</h2>
                <p className="text-sm text-slate-400">Set subscription fees, duration, payment details, and system behavior.</p>
              </div>
            </div>
            <button
              onClick={handleSave}
              disabled={saving}
              className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50"
            >
              <Save className="h-4 w-4" />
              {saving ? 'Saving...' : 'Save Settings'}
            </button>
          </div>

          <div className="p-5 space-y-6">
            {error && saving === false && (
              <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div>
            )}

            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div>
                <label className="mb-1 block text-sm font-medium text-slate-300">Subscription Fee ($)</label>
                <div className="relative">
                  <DollarSign className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
                  <input
                    type="number"
                    step="0.01"
                    min="0"
                    value={local.fee}
                    onChange={(e) => updateField('fee', e.target.value ? parseFloat(e.target.value) : 0)}
                    className="w-full rounded-lg border border-white/10 bg-white/5 pl-9 pr-4 py-2 text-white focus:border-blue-500 focus:outline-none"
                  />
                </div>
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium text-slate-300">Currency</label>
                <input
                  type="text"
                  value={paymentDetails.currency || local.currency}
                  onChange={(e) => handlePaymentField('currency', e.target.value)}
                  className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
                  placeholder={sysConfig.currency}
                />
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium text-slate-300">Subscription Duration (days)</label>
                <div className="relative">
                  <Clock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
                  <input
                    type="number"
                    min={1}
                    value={local.durationDays}
                    onChange={(e) => updateField('durationDays', parseInt(e.target.value, 10) || 0)}
                    className="w-full rounded-lg border border-white/10 bg-white/5 pl-9 pr-4 py-2 text-white focus:border-blue-500 focus:outline-none"
                  />
                </div>
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium text-slate-300">Grace Period (days)</label>
                <div className="relative">
                  <Clock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
                  <input
                    type="number"
                    min={0}
                    value={local.gracePeriodDays}
                    onChange={(e) => updateField('gracePeriodDays', parseInt(e.target.value, 10) || 0)}
                    className="w-full rounded-lg border border-white/10 bg-white/5 pl-9 pr-4 py-2 text-white focus:border-blue-500 focus:outline-none"
                  />
                </div>
              </div>

              <div className="md:col-span-2">
                <p className="mb-3 text-xs font-medium uppercase text-slate-400">Payment Destination</p>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div>
                    <label className="mb-1 block text-sm font-medium text-slate-300">Wallet Address</label>
                    <div className="relative">
                      <Wallet className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
                      <input
                        type="text"
                        value={paymentDetails.walletAddress || ''}
                        onChange={(e) => handlePaymentField('walletAddress', e.target.value)}
                        className="w-full rounded-lg border border-white/10 bg-white/5 pl-9 pr-4 py-2 text-white font-mono text-xs focus:border-blue-500 focus:outline-none"
                        placeholder="0x..."
                      />
                    </div>
                  </div>
                  <div>
                    <label className="mb-1 block text-sm font-medium text-slate-300">Network / Chain</label>
                    <div className="relative">
                      <Network className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
                      <input
                        type="text"
                        value={paymentDetails.network || ''}
                        onChange={(e) => handlePaymentField('network', e.target.value)}
                        className="w-full rounded-lg border border-white/10 bg-white/5 pl-9 pr-4 py-2 text-white focus:border-blue-500 focus:outline-none"
                        placeholder="e.g. Ethereum, Solana"
                      />
                    </div>
                  </div>
                </div>
              </div>

              <div className="md:col-span-2">
                <p className="mb-3 text-xs font-medium uppercase text-slate-400">System Behavior</p>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div className="flex items-center gap-3 rounded-lg border border-white/10 bg-white/[0.02] p-4">
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-white/5 text-slate-400">
                      <ToggleRight className="h-5 w-5" />
                    </div>
                    <label className="flex cursor-pointer items-center gap-2">
                      <input
                        type="checkbox"
                        checked={local.renewalEnabled}
                        onChange={(e) => updateField('renewalEnabled', e.target.checked)}
                        className="h-4 w-4 rounded border-white/10 bg-white/5"
                      />
                      <div>
                        <span className="text-sm font-medium text-slate-300">Auto-Renewal Enabled</span>
                        <p className="text-xs text-slate-400">Automatically renew subscriptions when they expire.</p>
                      </div>
                    </label>
                  </div>

                  <div className="flex items-center gap-3 rounded-lg border border-white/10 bg-white/[0.02] p-4">
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-white/5 text-slate-400">
                      <Settings className="h-5 w-5" />
                    </div>
                    <label className="flex cursor-pointer items-center gap-2">
                      <input
                        type="checkbox"
                        checked={local.applyToExistingUsers}
                        onChange={(e) => updateField('applyToExistingUsers', e.target.checked)}
                        className="h-4 w-4 rounded border-white/10 bg-white/5"
                      />
                      <div>
                        <span className="text-sm font-medium text-slate-300">Apply to Existing Users</span>
                        <p className="text-xs text-slate-400">Apply subscription settings to current platform users.</p>
                      </div>
                    </label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="rounded-xl border border-white/10 bg-slate-900/50">
        <div className="flex items-center justify-between border-b border-white/10 p-5">
          <div>
            <h2 className="text-lg font-semibold text-white">User Subscriptions</h2>
            <p className="text-sm text-slate-400">View active and historical user subscriptions.</p>
          </div>
        </div>

        <div className="p-5">
          <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between mb-4">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
              <input
                type="text"
                placeholder="Search by user or plan..."
                value={subSearch}
                onChange={(e) => { setSubSearch(e.target.value); setSubPage(1); }}
                className="w-full rounded-lg border border-white/10 bg-white/5 pl-9 pr-4 py-2 text-sm text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none"
              />
            </div>
            <select
              value={subStatusFilter}
              onChange={(e) => { setSubStatusFilter(e.target.value as SubscriptionStatus | 'ALL'); setSubPage(1); }}
              className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
            >
              <option value="ALL">All Statuses</option>
              <option value="ACTIVE">Active</option>
              <option value="EXPIRED">Expired</option>
              <option value="TERMINATED">Terminated</option>
              <option value="GRACE">Grace</option>
              <option value="CANCELLED">Cancelled</option>
            </select>
          </div>

          {subLoading ? (
            <TableSkeleton rows={5} />
          ) : filteredSubs.length === 0 ? (
            <EmptyState message="No subscriptions found" description="No subscriptions match the current filters." />
          ) : (
            <>
              <div className="overflow-x-auto rounded-xl border border-white/10">
                <table className="w-full text-left text-sm">
                  <thead className="bg-white/5 text-xs uppercase text-slate-400">
                    <tr>
                      <th className="px-4 py-3">User</th>
                      <th className="px-4 py-3">Plan</th>
                      <th className="px-4 py-3">Status</th>
                      <th className="px-4 py-3">Start</th>
                      <th className="px-4 py-3">End</th>
                      <th className="px-4 py-3">Grace Period End</th>
                      <th className="px-4 py-3">Renewals</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {filteredSubs.map((sub) => (
                      <tr key={sub.id} className="hover:bg-white/5">
                        <td className="px-4 py-3 text-slate-300">{sub.user?.email || sub.userId}</td>
                        <td className="px-4 py-3 text-slate-300">{sub.plan?.name || sub.planId}</td>
                        <td className="px-4 py-3">
                          <span className={`rounded-full px-2 py-1 text-xs font-medium ${SUB_STATUS_COLORS[sub.status] || 'bg-slate-500/20 text-slate-300'}`}>
                            {sub.status}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-slate-300 whitespace-nowrap">{new Date(sub.startDate).toLocaleDateString()}</td>
                        <td className="px-4 py-3 text-slate-300 whitespace-nowrap">{new Date(sub.endDate).toLocaleDateString()}</td>
                        <td className="px-4 py-3 text-slate-300 whitespace-nowrap">
                          {sub.gracePeriodEnd ? new Date(sub.gracePeriodEnd).toLocaleDateString() : 'N/A'}
                        </td>
                        <td className="px-4 py-3 text-slate-300">{sub.renewalCount}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {subMeta && subMeta.total > subLimit && (
                <div className="mt-4 flex items-center justify-between">
                  <p className="text-xs text-slate-400">
                    Showing {(subPage - 1) * subLimit + 1}-{Math.min(subPage * subLimit, subMeta.total)} of {subMeta.total}
                  </p>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => setSubPage((prev) => Math.max(1, prev - 1))}
                      disabled={subPage === 1}
                      className="rounded-lg border border-white/10 px-3 py-1.5 text-sm text-slate-300 hover:bg-white/5 disabled:opacity-50"
                    >
                      Previous
                    </button>
                    <button
                      onClick={() => setSubPage((prev) => prev + 1)}
                      disabled={subPage * subLimit >= subMeta.total}
                      className="rounded-lg border border-white/10 px-3 py-1.5 text-sm text-slate-300 hover:bg-white/5 disabled:opacity-50"
                    >
                      Next
                    </button>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
