'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { TrendingUp, CheckCircle, AlertTriangle, ShieldOff, Wallet as WalletIcon, Lock, Info, Copy } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { formatCurrency } from '@/lib/utils';
import { getErrorMessage } from '@/lib/errors';
import { ordersService, type Order, type P2PTrade } from '@/services/orders.service';
import { walletService } from '@/services/wallet.service';
import { subscriptionService, type Subscription } from '@/services/subscription.service';
import { authService } from '@/services/auth.service';
import { useSystemConfig } from '@/hooks/useSystemConfig';

const STEPS = ['Select Currency', 'Enter Amount', 'Review & Sell'] as const;

const SUPPORTED_CURRENCIES = ['USDT'] as const;
type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number];

const SUPPORTED_CHAINS = ['TRC20', 'SOLANA'] as const;
type SupportedChain = (typeof SUPPORTED_CHAINS)[number];

const PRICE = 1;

const TRX_REGEX = /^T[a-zA-Z0-9]{33}$/;
const SOL_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;

function isValidAddressForChain(address: string, chain: SupportedChain): boolean {
  const trimmed = address.trim();
  if (chain === 'TRC20') return TRX_REGEX.test(trimmed);
  return SOL_REGEX.test(trimmed);
}

interface WalletState {
  balance: number;
  locked: number;
  available: number;
}

export default function SellPage() {
  const router = useRouter();
  const sysConfig = useSystemConfig();
  const [step, setStep] = useState(0);
  const [currency, setCurrency] = useState<SupportedCurrency>('USDT');
  const [quantity, setQuantity] = useState('');
  const [chain, setChain] = useState<SupportedChain>('TRC20');
  const [walletAddress, setWalletAddress] = useState('');
  const [message, setMessage] = useState('');

  const [wallet, setWallet] = useState<WalletState | null>(null);
  const [subscription, setSubscription] = useState<Subscription | null>(null);
  const [userFrozen, setUserFrozen] = useState(false);
  const [bootstrap, setBootstrap] = useState(true);

  const [selling, setSelling] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [matching, setMatching] = useState(false);
  const [trade, setTrade] = useState<P2PTrade | null>(null);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      setBootstrap(true);
      try {
        const [w, sub, me] = await Promise.allSettled([
          walletService.getBalance(),
          subscriptionService.getMySubscription(),
          authService.getProfile(),
        ]);
        if (cancelled) return;
        if (w.status === 'fulfilled') {
          setWallet({
            balance: Number(w.value.balance) || 0,
            locked: Number(w.value.locked) || 0,
            available: Number(w.value.available) || 0,
          });
        }
        if (sub.status === 'fulfilled') {
          setSubscription(sub.value ?? null);
        }
        if (me.status === 'fulfilled') {
          const profile = (me.value as any)?.data?.data?.user ?? (me.value as any)?.data?.data ?? (me.value as any)?.data?.user ?? (me.value as any)?.data;
          setUserFrozen(Boolean(profile?.isFrozen));
          if (profile?.usdtWalletAddress) setWalletAddress(profile.usdtWalletAddress);
        }
      } finally {
        if (!cancelled) setBootstrap(false);
      }
    };
    load();
    return () => {
      cancelled = true;
    };
  }, []);

  const numericQty = Number(quantity) || 0;
  const totalUsdt = numericQty * PRICE;

  const subExpired = subscription?.status === 'EXPIRED' || subscription?.status === 'TERMINATED' || subscription?.status === 'CANCELLED';
  const isBlocked = userFrozen || subExpired;
  const insufficient = wallet ? numericQty > wallet.available : false;
  const walletAddressValid = walletAddress.trim() !== '' && isValidAddressForChain(walletAddress, chain);

  const resetFlow = () => {
    setStep(0);
    setQuantity('');
    setMessage('');
    setChain('TRC20');
    setTrade(null);
  };

  const handleConfirm = async () => {
    if (numericQty <= 0) {
      setError('Amount must be greater than zero.');
      return;
    }
    if (isBlocked) {
      setError(userFrozen ? 'Your account is frozen. Selling is disabled.' : 'Your subscription is not active. Please renew to sell.');
      return;
    }
    if (!walletAddressValid) {
      setError('Please provide a valid wallet address for the selected chain.');
      return;
    }
    if (wallet && numericQty > wallet.available) {
      setError(`Insufficient available balance. You have ${formatCurrency(wallet.available)} ${currency} available.`);
      return;
    }

    setSelling(true);
    setError(null);
    try {
      const order: Order = await ordersService.sell({
        currency,
        price: PRICE,
        quantity: numericQty,
        walletAddress: walletAddress.trim(),
      });
      setSuccess(true);
      setSelling(false);

      setMatching(true);
      try {
        const result = await ordersService.p2pFindMatch({
          amount: numericQty,
          platform: 'internal',
          side: 'SELL',
          network: chain,
        });
        setTrade(result);
      } catch (err) {
        setError(getErrorMessage(err));
      } finally {
        setMatching(false);
      }

      setTimeout(() => {
        if (order?.id) router.push(`/dashboard/orders/${order.id}`);
        else router.push('/dashboard');
      }, 1200);
    } catch (err) {
      setError(getErrorMessage(err));
      setSelling(false);
    }
  };

  if (bootstrap) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-32 w-full" />
        <Skeleton className="h-64 w-full" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight text-ink">Sell {currency}</h1>
        <p className="mt-1 text-sm text-ink-muted">
          List your crypto for sale. Funds are debited when the order matches.
        </p>
      </div>

      {wallet && (
        <Card>
          <CardContent className="flex items-center justify-between p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary-500/10 text-primary-600">
                <WalletIcon className="h-5 w-5" />
              </div>
              <div>
                <p className="text-xs text-ink-muted">Available balance</p>
                <p className="text-lg font-semibold text-ink">{formatCurrency(wallet.available)}</p>
              </div>
            </div>
            <div className="text-right text-xs text-ink-muted">
              <p>Locked: {formatCurrency(wallet.locked)}</p>
              <p>Total: {formatCurrency(wallet.balance)}</p>
            </div>
          </CardContent>
        </Card>
      )}

      {isBlocked && (
        <div className="flex items-start gap-2 rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-300">
          {userFrozen ? <ShieldOff className="mt-0.5 h-4 w-4 shrink-0" /> : <Lock className="mt-0.5 h-4 w-4 shrink-0" />}
          <div>
            <p className="font-medium">
              {userFrozen ? 'Your account is frozen.' : 'Your subscription is not active.'}
            </p>
            <p className="text-xs opacity-90">
              {userFrozen
                ? 'Selling is disabled while your account is frozen. Please contact support.'
                : 'Renew your subscription to resume selling.'}
            </p>
          </div>
        </div>
      )}

      <div className="flex items-center gap-2">
        {STEPS.map((s, i) => (
          <div key={s} className="flex items-center gap-2">
            <div className={`flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium ${
              i === step ? 'bg-primary-600 text-white' : i < step ? 'bg-emerald-500 text-white' : 'bg-surface-raised text-ink-muted'
            }`}>
              {i < step ? <CheckCircle className="h-4 w-4" /> : i + 1}
            </div>
            <span className={`text-sm ${i === step ? 'font-medium text-ink' : 'text-ink-muted'}`}>{s}</span>
            {i < STEPS.length - 1 && <div className="w-4 border-t border-line"></div>}
          </div>
        ))}
      </div>

      {matching && (
        <div className="flex items-center gap-2 rounded-xl border border-primary-500/30 bg-primary-500/10 p-3 text-sm text-primary-700 dark:text-primary-300">
          <Info className="h-4 w-4 shrink-0" />
          Searching for a buyer match…
        </div>
      )}

      {trade && (
        <Card className="border-emerald-500/30 bg-emerald-500/5">
          <CardContent className="p-4 space-y-2">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-emerald-700 dark:text-emerald-300">Buyer matched</p>
                <p className="font-medium text-ink">{trade.buyer?.email ?? 'Match found'}</p>
              </div>
              <Badge variant="success">Matched</Badge>
            </div>
            <p className="text-xs text-ink-muted">Trade ID: {trade.id}</p>
          </CardContent>
        </Card>
      )}

      {success && !trade && !matching && (
        <div className="flex items-center gap-2 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-700 dark:text-emerald-300">
          <CheckCircle className="h-4 w-4" />
          Sell order created. Redirecting to order details...
        </div>
      )}

      {error && (
        <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-600 dark:text-red-300">
          {error}
        </div>
      )}

      {step === 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Select Currency</CardTitle>
            <CardDescription className="mt-1">Choose the crypto you want to sell</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {SUPPORTED_CURRENCIES.map((c) => (
              <button
                key={c}
                type="button"
                onClick={() => setCurrency(c)}
                className={`w-full rounded-xl border px-4 py-3 text-left text-sm font-medium transition ${
                  currency === c
                    ? 'border-primary-500 bg-primary-500/10 text-ink'
                    : 'border-line bg-surface text-ink-muted hover:border-ink/20'
                }`}
              >
                {c}
              </button>
            ))}
            <div className="flex justify-end">
              <Button onClick={() => setStep(1)} disabled={!currency}>Continue</Button>
            </div>
          </CardContent>
        </Card>
      )}

      {step === 1 && (
        <Card>
          <CardHeader>
            <CardTitle>Enter Amount</CardTitle>
            <CardDescription className="mt-1">How much {currency} do you want to sell?</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-ink mb-2">Amount ({currency})</label>
              <div className="relative">
                <input
                  type="number"
                  inputMode="decimal"
                  min="0"
                  step="0.0001"
                  placeholder="0.00"
                  value={quantity}
                  onChange={(e) => setQuantity(e.target.value)}
                  className="w-full pl-4 pr-16 py-3 rounded-xl border border-line bg-surface text-ink text-2xl font-medium focus:outline-none focus:ring-2 focus:ring-primary-500"
                />
                <span className="absolute right-4 top-1/2 -translate-y-1/2 text-sm font-medium text-ink-muted">{currency}</span>
              </div>
              {wallet && (
                <p className="mt-1 text-xs text-ink-faint">
                  Available: {formatCurrency(wallet.available)} {currency}
                </p>
              )}
            </div>
            <div className="flex gap-2">
              {wallet && wallet.available > 0 && [25, 50, 75, 100].map((pct) => (
                <button
                  key={pct}
                  type="button"
                  onClick={() => setQuantity(((wallet.available * pct) / 100).toFixed(4))}
                  className="flex-1 rounded-lg border border-line bg-surface-raised px-2 py-1.5 text-xs font-medium text-ink-muted hover:text-ink hover:border-ink/20"
                >
                  {pct}%
                </button>
              ))}
            </div>
            <div>
              <label className="block text-sm font-medium text-ink mb-2">Crypto Chain <span className="text-red-500">*</span></label>
               <div className="flex gap-3">
                 <button
                   type="button"
                   onClick={() => setChain('TRC20')}
                   className={`flex-1 rounded-xl border px-4 py-3 text-center text-sm font-medium transition ${
                     chain === 'TRC20'
                       ? 'border-primary-500 bg-primary-500/10 text-ink'
                       : 'border-line bg-surface text-ink-muted hover:border-ink/20'
                   }`}
                 >
                   TRC20
                 </button>
                 <button
                   type="button"
                   onClick={() => setChain('SOLANA')}
                   className={`flex-1 rounded-xl border px-4 py-3 text-center text-sm font-medium transition ${
                     chain === 'SOLANA'
                       ? 'border-primary-500 bg-primary-500/10 text-ink'
                       : 'border-line bg-surface text-ink-muted hover:border-ink/20'
                   }`}
                 >
                   Solana
                  </button>
                </div>
                <p className="mt-1 text-xs text-ink-faint">
                  Select the blockchain network for receiving USDT.
                </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-ink mb-2">
                Your {currency} receiving wallet address <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                 <input
                   type="text"
                   value={walletAddress}
                   onChange={(e) => setWalletAddress(e.target.value)}
                   placeholder={chain === 'TRC20' ? 'TRC20 T...' : 'Solana base58 address...'}
                   className="w-full rounded-xl border border-line bg-surface pl-4 pr-12 py-2 text-ink font-mono text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                 />
                {walletAddress && (
                  <button
                    type="button"
                    onClick={() => navigator.clipboard?.writeText(walletAddress)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1 text-ink-muted hover:text-ink"
                    aria-label="Copy"
                  >
                    <Copy className="h-4 w-4" />
                  </button>
                )}
              </div>
              {walletAddress && !walletAddressValid && (
                <p className="mt-1 text-xs text-red-500">Invalid wallet address format</p>
              )}
              <p className="mt-1 text-xs text-ink-faint">
                This address will be shown to the matched buyer for {currency} transfer.
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-ink mb-2">Message to buyer (optional)</label>
              <textarea
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                rows={3}
                placeholder="Add any notes for the buyer (e.g. payment window, terms)…"
                className="w-full rounded-xl border border-line bg-surface px-4 py-2 text-ink focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none"
              />
            </div>
            {numericQty > 0 && (
              <div className="rounded-xl bg-surface-raised p-3 text-sm text-ink-muted">
                Total: <span className="font-semibold text-ink">{formatCurrency(totalUsdt)} USDT</span>
              </div>
            )}
            {insufficient && (
              <div className="flex items-start gap-2 rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-300">
                <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
                <span>Amount exceeds your available balance of {formatCurrency(wallet?.available ?? 0)} {currency}.</span>
              </div>
            )}
            <div className="flex justify-between gap-2">
              <Button variant="outline" onClick={() => setStep(0)}>Back</Button>
              <Button onClick={() => setStep(2)} disabled={!quantity || numericQty <= 0 || insufficient || !walletAddressValid}>
                Continue
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {step === 2 && (
        <Card>
          <CardHeader>
            <CardTitle>Review Sale</CardTitle>
            <CardDescription className="mt-1">Confirm your sale details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
             <div className="space-y-3">
              <div className="flex justify-between">
                <span className="text-ink-muted">Currency</span>
                <span className="font-medium text-ink">{currency}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-ink-muted">Chain</span>
                <span className="font-medium text-ink">{chain}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-ink-muted">Quantity</span>
                <span className="font-medium text-ink">{numericQty} {currency}</span>
              </div>
              <div className="flex justify-between border-t border-line pt-2">
                <span className="text-ink-muted">Total (USDT)</span>
                <span className="font-semibold text-ink">{formatCurrency(totalUsdt)}</span>
              </div>
              <div className="flex justify-between text-xs text-ink-muted">
                <span>Receive at</span>
                <span className="font-mono truncate max-w-[60%]">{walletAddress}</span>
              </div>
              {message && (
                <div className="rounded-lg bg-surface-raised p-2 text-xs text-ink-muted">
                  <span className="font-medium text-ink">Note to buyer:</span> {message}
                </div>
              )}
              {wallet && (
                <div className="flex justify-between text-xs text-ink-muted">
                  <span>After this order, available balance will be</span>
                  <span>{formatCurrency(Math.max(0, wallet.available - numericQty))}</span>
                </div>
              )}
            </div>
            <div className="flex justify-between gap-2">
              <Button variant="outline" onClick={() => setStep(1)} disabled={selling}>Back</Button>
              <Button
                onClick={handleConfirm}
                disabled={selling || matching || isBlocked || insufficient}
                className="flex items-center gap-2"
              >
                {selling ? 'Creating...' : matching ? 'Matching...' : 'Confirm Sale'}
                {!selling && !matching && <TrendingUp className="h-4 w-4" />}
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {success && (
        <div className="text-center">
          <Button variant="ghost" size="sm" onClick={resetFlow}>
            Place another sell order
          </Button>
        </div>
      )}
    </div>
  );
}
