'use client';

import { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Brain,
  Search,
  AlertTriangle,
  ShieldCheck,
  ShieldAlert,
  ShieldX,
  CheckCircle2,
  XCircle,
  Lightbulb,
  Copy,
  Sparkles,
  RotateCcw,
  ChevronRight,
} from 'lucide-react';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Progress } from '@/components/ui/progress';
import { useAppStore } from '@/store/app-store';
import { toast } from 'sonner';

// ─── Types ──────────────────────────────────────────────────────────────────

interface AnalysisResult {
  scamProbability: number;
  riskLevel: 'low' | 'medium' | 'high' | 'critical';
  indicators: { type: string; message: string; severity: 'info' | 'warning' | 'danger' }[];
  recommendations: string[];
}

// ─── Pattern Definitions ────────────────────────────────────────────────────

const URGENCY_PATTERNS = [
  { pattern: /\burgent\b/i, message: 'Urgency language detected', weight: 15 },
  { pattern: /\bimmediately\b/i, message: 'Immediate action demanded', weight: 15 },
  { pattern: /\bhurry\b/i, message: 'Hurry pressure detected', weight: 12 },
  { pattern: /\blimited\s*time\b/i, message: 'Limited time offer pressure', weight: 14 },
  { pattern: /\bact\s*now\b/i, message: '"Act now" pressure detected', weight: 14 },
  { pattern: /\bASAP\b/i, message: 'ASAP urgency detected', weight: 10 },
  { pattern: /\bdeadline\b/i, message: 'Deadline pressure detected', weight: 10 },
  { pattern: /\bexpire/i, message: 'Expiration threat detected', weight: 12 },
  { pattern: /\blast\s*chance\b/i, message: '"Last chance" pressure detected', weight: 13 },
  { pattern: /\bnow\b.{0,20}(or|otherwise|else)/i, message: 'Consequential urgency detected', weight: 14 },
];

const PAYMENT_PATTERNS = [
  { pattern: /\bb[kK]ash\b/i, message: 'bKash payment reference detected', weight: 12 },
  { pattern: /\bnagad\b/i, message: 'Nagad payment reference detected', weight: 12 },
  { pattern: /\bsend\s*money\b/i, message: 'Money transfer request detected', weight: 18 },
  { pattern: /\bpayment\b/i, message: 'Payment request detected', weight: 10 },
  { pattern: /\btransfer\b/i, message: 'Transfer request detected', weight: 12 },
  { pattern: /\badvance\b/i, message: 'Advance payment request detected', weight: 16 },
  { pattern: /\bdeposit\b/i, message: 'Deposit request detected', weight: 12 },
  { pattern: /\bcash\s*out\b/i, message: 'Cash out request detected', weight: 10 },
  { pattern: /\bpay\s*(now|first|before|upfront)\b/i, message: 'Upfront payment demand detected', weight: 16 },
  { pattern: /\baccount\s*number\b/i, message: 'Account number request detected', weight: 10 },
];

const TOO_GOOD_PATTERNS = [
  { pattern: /\bdouble\b.{0,20}(money|payment|return|profit)/i, message: 'Double money scheme detected', weight: 20 },
  { pattern: /\bguaranteed\s*return\b/i, message: 'Guaranteed return promise detected', weight: 18 },
  { pattern: /\bfree\b.{0,20}(money|cash|gift|prize)/i, message: 'Free money/gift promise detected', weight: 18 },
  { pattern: /\bwin\b.{0,15}(prize|lottery|reward)/i, message: 'Prize/lottery winning claim detected', weight: 20 },
  { pattern: /\blottery\b/i, message: 'Lottery reference detected', weight: 18 },
  { pattern: /\bprize\b/i, message: 'Prize claim detected', weight: 14 },
  { pattern: /\bjackpot\b/i, message: 'Jackpot claim detected', weight: 18 },
  { pattern: /\b10[xX]\b|\b5[xX]\b|\b3[xX]\s*return/i, message: 'Unrealistic return multiplier detected', weight: 20 },
  { pattern: /\binvest\b.{0,30}(double|triple|multiply)/i, message: 'Investment multiplication scheme detected', weight: 20 },
  { pattern: /\bprofit.{0,15}(guaranteed|sure|certain)/i, message: 'Guaranteed profit promise detected', weight: 18 },
];

const SUSPICIOUS_CONTACT_PATTERNS = [
  { pattern: /\bWhatsApp\b/i, message: 'WhatsApp contact method detected', weight: 8 },
  { pattern: /\bTelegram\b/i, message: 'Telegram contact method detected', weight: 8 },
  { pattern: /\bdon'?t\s*call\b/i, message: '"Don\'t call" instruction detected', weight: 15 },
  { pattern: /\bsecret\b/i, message: 'Secrecy request detected', weight: 12 },
  { pattern: /\bconfidential\b/i, message: 'Confidentiality demand detected', weight: 10 },
  { pattern: /\bprivate\s*(message|chat|group)/i, message: 'Private communication request detected', weight: 10 },
  { pattern: /\bonly\s*(contact|message|chat|call)/i, message: 'Exclusive contact restriction detected', weight: 10 },
];

const PERSONAL_INFO_PATTERNS = [
  { pattern: /\bOTP\b/i, message: 'OTP request detected — never share your OTP!', weight: 25 },
  { pattern: /\bPIN\b/i, message: 'PIN request detected — never share your PIN!', weight: 25 },
  { pattern: /\bpassword\b/i, message: 'Password request detected — never share your password!', weight: 22 },
  { pattern: /\bbank\s*(details|info|information)\b/i, message: 'Bank details request detected', weight: 20 },
  { pattern: /\bNID\b/i, message: 'NID (National ID) request detected', weight: 15 },
  { pattern: /\bverification\b.{0,20}(code|OTP|PIN)/i, message: 'Verification code request detected', weight: 20 },
  { pattern: /\baccount\s*(details|info|verification)\b/i, message: 'Account information request detected', weight: 18 },
  { pattern: /\bKYC\b/i, message: 'KYC information request detected', weight: 15 },
];

// ─── Sample Texts ───────────────────────────────────────────────────────────

const SAMPLE_TEXTS = [
  {
    title: 'Fake Lottery Win',
    text: 'Congratulations! You have won 5,00,000 Taka in the Bangladesh National Lottery! To claim your prize, please send your bKash number and a 500 Taka processing fee immediately. This offer expires in 24 hours! Act now or you will lose your winnings. Contact us on WhatsApp only.',
  },
  {
    title: 'Investment Scam',
    text: 'Double your money in just 7 days! Guaranteed return on investment. Send money via bKash or Nagad and get 3X return. Limited time offer - don\'t miss this opportunity. Join our secret Telegram group for VIP investment tips. Hurry, only a few spots left!',
  },
  {
    title: 'Phishing Message',
    text: 'Dear customer, your bKash account will be suspended immediately. Please verify your account by providing your OTP, PIN, and bank details. Act now to avoid account closure. Do not call our official number, only reply to this message.',
  },
  {
    title: 'Normal Message',
    text: 'Hi, I saw your listing for the Samsung Galaxy S23 on Bikroy.com. Is it still available? I can pick it up from Dhaka this weekend. Please let me know the final price and your location.',
  },
];

// ─── Analysis Engine ────────────────────────────────────────────────────────

function analyzeText(text: string): AnalysisResult {
  const indicators: AnalysisResult['indicators'] = [];
  let score = 0;

  // Check all pattern groups
  const allGroups = [
    { patterns: URGENCY_PATTERNS, type: 'urgency' },
    { patterns: PAYMENT_PATTERNS, type: 'payment' },
    { patterns: TOO_GOOD_PATTERNS, type: 'too-good' },
    { patterns: SUSPICIOUS_CONTACT_PATTERNS, type: 'contact' },
    { patterns: PERSONAL_INFO_PATTERNS, type: 'personal-info' },
  ];

  for (const group of allGroups) {
    for (const { pattern, message, weight } of group.patterns) {
      if (pattern.test(text)) {
        score += weight;
        indicators.push({
          type: group.type,
          message,
          severity: weight >= 18 ? 'danger' : weight >= 12 ? 'warning' : 'info',
        });
      }
    }
  }

  // Deduplicate indicators by message
  const seen = new Set<string>();
  const uniqueIndicators = indicators.filter((ind) => {
    if (seen.has(ind.message)) return false;
    seen.add(ind.message);
    return true;
  });

  // Cap the score at 100
  const scamProbability = Math.min(100, score);

  // Determine risk level
  let riskLevel: AnalysisResult['riskLevel'] = 'low';
  if (scamProbability > 80) riskLevel = 'critical';
  else if (scamProbability > 60) riskLevel = 'high';
  else if (scamProbability > 30) riskLevel = 'medium';

  // Generate recommendations based on findings
  const recommendations: string[] = [];

  if (uniqueIndicators.some((i) => i.type === 'personal-info')) {
    recommendations.push('Never share OTP, PIN, or password with anyone — legitimate organizations will never ask for these.');
  }
  if (uniqueIndicators.some((i) => i.type === 'payment')) {
    recommendations.push('Do not send money to unknown persons. Verify the recipient through official channels first.');
  }
  if (uniqueIndicators.some((i) => i.type === 'urgency')) {
    recommendations.push('Scammers create urgency to prevent you from thinking clearly. Take your time and verify independently.');
  }
  if (uniqueIndicators.some((i) => i.type === 'too-good')) {
    recommendations.push('If it sounds too good to be true, it probably is. There are no guaranteed ways to double your money quickly.');
  }
  if (uniqueIndicators.some((i) => i.type === 'contact')) {
    recommendations.push('Be cautious of requests to communicate only through private channels like WhatsApp or Telegram.');
  }
  if (recommendations.length === 0) {
    recommendations.push('This message appears relatively safe, but always stay vigilant.');
    recommendations.push('Verify unknown contacts through official channels before engaging.');
    recommendations.push('Search the phone number or bKash number on ScamChecker BD before making transactions.');
  }

  // Always add these general tips
  recommendations.push('Search the sender\'s number or bKash on ScamChecker BD to check for existing reports.');
  recommendations.push('Report this message on ScamChecker BD if you believe it is a scam.');

  return {
    scamProbability,
    riskLevel,
    indicators: uniqueIndicators,
    recommendations,
  };
}

// ─── Risk Level Config ──────────────────────────────────────────────────────

const riskLevelConfig: Record<
  string,
  {
    label: string;
    color: string;
    bg: string;
    borderColor: string;
    icon: React.ElementType;
    progressColor: string;
  }
> = {
  low: {
    label: 'Low Risk',
    color: 'text-emerald-600 dark:text-emerald-400',
    bg: 'bg-emerald-500/10',
    borderColor: 'border-emerald-500/30',
    icon: ShieldCheck,
    progressColor: 'bg-emerald-500',
  },
  medium: {
    label: 'Medium Risk',
    color: 'text-yellow-600 dark:text-yellow-400',
    bg: 'bg-yellow-500/10',
    borderColor: 'border-yellow-500/30',
    icon: ShieldAlert,
    progressColor: 'bg-yellow-500',
  },
  high: {
    label: 'High Risk',
    color: 'text-orange-600 dark:text-orange-400',
    bg: 'bg-orange-500/10',
    borderColor: 'border-orange-500/30',
    icon: ShieldX,
    progressColor: 'bg-orange-500',
  },
  critical: {
    label: 'Critical Risk',
    color: 'text-red-600 dark:text-red-400',
    bg: 'bg-red-500/10',
    borderColor: 'border-red-500/30',
    icon: AlertTriangle,
    progressColor: 'bg-red-500',
  },
};

const severityConfig: Record<string, { color: string; bg: string; icon: React.ElementType }> = {
  info: {
    color: 'text-blue-600 dark:text-blue-400',
    bg: 'bg-blue-500/10',
    icon: Search,
  },
  warning: {
    color: 'text-yellow-600 dark:text-yellow-400',
    bg: 'bg-yellow-500/10',
    icon: AlertTriangle,
  },
  danger: {
    color: 'text-red-600 dark:text-red-400',
    bg: 'bg-red-500/10',
    icon: XCircle,
  },
};

// ─── Animation Variants ─────────────────────────────────────────────────────

const containerVariants = {
  hidden: {},
  visible: { transition: { staggerChildren: 0.08 } },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.4, ease: 'easeOut' } },
};

// ─── Main Component ─────────────────────────────────────────────────────────

export function AIDetectPage() {
  const navigate = useAppStore((s) => s.navigate);
  const [inputText, setInputText] = useState('');
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [result, setResult] = useState<AnalysisResult | null>(null);

  const handleAnalyze = useCallback(async () => {
    if (!inputText.trim()) {
      toast.error('Please enter some text to analyze');
      return;
    }

    setIsAnalyzing(true);
    setResult(null);

    try {
      // Try real LLM backend first
      const res = await fetch('/api/ai-detect', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: inputText }),
      });
      const data = await res.json();
      if (data.success && data.data) {
        setResult(data.data);
      } else {
        // Fallback to client-side analysis
        const analysis = analyzeText(inputText);
        setResult(analysis);
      }
    } catch {
      // Fallback to client-side analysis on error
      const analysis = analyzeText(inputText);
      setResult(analysis);
    } finally {
      setIsAnalyzing(false);
    }
  }, [inputText]);

  const handleReset = useCallback(() => {
    setInputText('');
    setResult(null);
  }, []);

  const handleSampleClick = useCallback((text: string) => {
    setInputText(text);
    setResult(null);
  }, []);

  const handleCopyResult = useCallback(() => {
    if (!result) return;
    const text = `Scam Probability: ${result.scamProbability}%\nRisk Level: ${result.riskLevel}\n\nIndicators:\n${result.indicators.map((i) => `- ${i.message}`).join('\n')}\n\nRecommendations:\n${result.recommendations.map((r) => `- ${r}`).join('\n')}`;
    navigator.clipboard.writeText(text).then(() => {
      toast.success('Analysis result copied to clipboard');
    });
  }, [result]);

  const probabilityColor = result
    ? result.scamProbability <= 30
      ? 'text-emerald-500'
      : result.scamProbability <= 60
        ? 'text-yellow-500'
        : result.scamProbability <= 80
          ? 'text-orange-500'
          : 'text-red-500'
    : '';

  const probabilityProgressColor = result
    ? result.scamProbability <= 30
      ? '[&>div]:bg-emerald-500'
      : result.scamProbability <= 60
        ? '[&>div]:bg-yellow-500'
        : result.scamProbability <= 80
          ? '[&>div]:bg-orange-500'
          : '[&>div]:bg-red-500'
    : '';

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
      <motion.div variants={containerVariants} initial="hidden" animate="visible">
        {/* ─── Header ────────────────────────────────────────────────────── */}
        <motion.div variants={itemVariants} className="mb-8 text-center">
          <motion.div
            className="inline-flex p-4 rounded-2xl bg-emerald-500/10 mb-4"
            animate={{
              boxShadow: [
                '0 0 0 0 oklch(0.558 0.158 155 / 0)',
                '0 0 20px 4px oklch(0.558 0.158 155 / 0.15)',
                '0 0 0 0 oklch(0.558 0.158 155 / 0)',
              ],
            }}
            transition={{ duration: 3, repeat: Infinity, ease: 'easeInOut' }}
          >
            <Brain className="h-10 w-10 text-emerald-500" />
          </motion.div>
          <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold mb-3">
            AI Scam Detector
          </h1>
          <p className="text-muted-foreground text-base sm:text-lg max-w-2xl mx-auto">
            Paste a suspicious message and our AI will analyze it for potential scam indicators
          </p>
        </motion.div>

        {/* ─── Input Section ──────────────────────────────────────────────── */}
        <motion.div variants={itemVariants}>
          <Card className="glass border-0 shadow-lg">
            <CardContent className="p-4 sm:p-6">
              <Textarea
                placeholder="Paste a suspicious message, email, SMS, or chat here..."
                value={inputText}
                onChange={(e) => setInputText(e.target.value)}
                rows={6}
                className="text-base resize-none border-emerald-500/20 focus-visible:border-emerald-500/60 focus-visible:ring-emerald-500/20"
                disabled={isAnalyzing}
              />

              <div className="flex flex-col sm:flex-row items-center gap-3 mt-4">
                <Button
                  size="lg"
                  onClick={handleAnalyze}
                  disabled={isAnalyzing || !inputText.trim()}
                  className="h-12 px-8 text-base rounded-xl bg-emerald-600 hover:bg-emerald-700 dark:bg-emerald-500 dark:hover:bg-emerald-600 shadow-lg shadow-emerald-500/20 w-full sm:w-auto"
                >
                  {isAnalyzing ? (
                    <>
                      <motion.div
                        animate={{ rotate: 360 }}
                        transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}
                      >
                        <Sparkles className="h-5 w-5" />
                      </motion.div>
                      Analyzing...
                    </>
                  ) : (
                    <>
                      <Brain className="h-5 w-5" />
                      Analyze
                    </>
                  )}
                </Button>

                {result && (
                  <Button
                    size="lg"
                    variant="outline"
                    onClick={handleReset}
                    className="h-12 px-6 text-base rounded-xl w-full sm:w-auto"
                  >
                    <RotateCcw className="h-5 w-5" />
                    Reset
                  </Button>
                )}
              </div>
            </CardContent>
          </Card>
        </motion.div>

        {/* ─── Sample Texts ───────────────────────────────────────────────── */}
        <motion.div variants={itemVariants} className="mt-6">
          <p className="text-sm font-medium text-muted-foreground mb-3">
            Try a sample message:
          </p>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {SAMPLE_TEXTS.map((sample, idx) => (
              <motion.button
                key={idx}
                onClick={() => handleSampleClick(sample.text)}
                className="text-left group"
                whileHover={{ scale: 1.01 }}
                whileTap={{ scale: 0.99 }}
              >
                <Card className="border border-border/50 hover:border-emerald-500/30 transition-all duration-200 h-full card-themed">
                  <CardContent className="p-3 sm:p-4">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-semibold group-hover:text-emerald-500 transition-colors">
                        {sample.title}
                      </span>
                      <ChevronRight className="h-4 w-4 text-muted-foreground group-hover:text-emerald-500 transition-colors" />
                    </div>
                    <p className="text-xs text-muted-foreground line-clamp-2">
                      {sample.text}
                    </p>
                  </CardContent>
                </Card>
              </motion.button>
            ))}
          </div>
        </motion.div>

        {/* ─── Analysis Results ───────────────────────────────────────────── */}
        <AnimatePresence mode="wait">
          {result && (
            <motion.div
              key="results"
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.5, ease: 'easeOut' }}
              className="mt-6 space-y-4 sm:space-y-6"
            >
              {/* ── Scam Probability Card ── */}
              <Card className={`glass border-0 shadow-lg ${result.riskLevel === 'critical' ? 'ring-2 ring-red-500/30' : result.riskLevel === 'high' ? 'ring-2 ring-orange-500/30' : ''}`}>
                <CardContent className="p-6 sm:p-8">
                  <div className="flex flex-col items-center text-center">
                    <p className="text-sm font-medium text-muted-foreground mb-2">
                      Scam Probability
                    </p>
                    <motion.div
                      className={`text-6xl sm:text-7xl font-extrabold ${probabilityColor}`}
                      initial={{ scale: 0.5, opacity: 0 }}
                      animate={{ scale: 1, opacity: 1 }}
                      transition={{ delay: 0.2, duration: 0.5, type: 'spring' }}
                    >
                      {result.scamProbability}%
                    </motion.div>
                    <div className="w-full max-w-md mt-4">
                      <Progress
                        value={result.scamProbability}
                        className={`h-3 ${probabilityProgressColor}`}
                      />
                    </div>
                    <div className="mt-4">
                      {(() => {
                        const config = riskLevelConfig[result.riskLevel];
                        const Icon = config.icon;
                        return (
                          <Badge
                            variant="outline"
                            className={`text-sm px-4 py-1.5 ${config.color} ${config.borderColor} ${config.bg}`}
                          >
                            <Icon className="h-4 w-4" />
                            {config.label}
                          </Badge>
                        );
                      })()}
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* ── Two Column: Indicators & Recommendations ── */}
              <div className="grid md:grid-cols-2 gap-4 sm:gap-6">
                {/* ── Detected Indicators ── */}
                <Card className="glass border-0 shadow-lg">
                  <CardHeader className="pb-3">
                    <CardTitle className="flex items-center gap-2 text-lg">
                      <AlertTriangle className="h-5 w-5 text-orange-500" />
                      Detected Indicators
                      <Badge variant="secondary" className="ml-auto text-xs">
                        {result.indicators.length}
                      </Badge>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {result.indicators.length === 0 ? (
                      <p className="text-sm text-muted-foreground text-center py-4">
                        No suspicious indicators detected
                      </p>
                    ) : (
                      <div className="space-y-2 max-h-72 overflow-y-auto custom-scrollbar">
                        {result.indicators.map((indicator, idx) => {
                          const config = severityConfig[indicator.severity];
                          const Icon = config.icon;
                          return (
                            <motion.div
                              key={idx}
                              initial={{ opacity: 0, x: -10 }}
                              animate={{ opacity: 1, x: 0 }}
                              transition={{ delay: 0.1 + idx * 0.05 }}
                              className={`flex items-start gap-2.5 p-2.5 rounded-lg ${config.bg}`}
                            >
                              <Icon className={`h-4 w-4 mt-0.5 shrink-0 ${config.color}`} />
                              <span className="text-sm">{indicator.message}</span>
                            </motion.div>
                          );
                        })}
                      </div>
                    )}
                  </CardContent>
                </Card>

                {/* ── Safety Recommendations ── */}
                <Card className="glass border-0 shadow-lg">
                  <CardHeader className="pb-3">
                    <CardTitle className="flex items-center gap-2 text-lg">
                      <Lightbulb className="h-5 w-5 text-emerald-500" />
                      Safety Recommendations
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2 max-h-72 overflow-y-auto custom-scrollbar">
                      {result.recommendations.map((rec, idx) => (
                        <motion.div
                          key={idx}
                          initial={{ opacity: 0, x: -10 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: 0.2 + idx * 0.05 }}
                          className="flex items-start gap-2.5 p-2.5 rounded-lg bg-emerald-500/5"
                        >
                          <CheckCircle2 className="h-4 w-4 mt-0.5 shrink-0 text-emerald-500" />
                          <span className="text-sm">{rec}</span>
                        </motion.div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* ── Action Buttons ── */}
              <div className="flex flex-col sm:flex-row gap-3">
                <Button
                  variant="outline"
                  onClick={handleCopyResult}
                  className="rounded-xl border-emerald-500/30 hover:bg-emerald-500/10"
                >
                  <Copy className="h-4 w-4" />
                  Copy Analysis
                </Button>
                <Button
                  onClick={() => navigate('report')}
                  className="rounded-xl bg-emerald-600 hover:bg-emerald-700"
                >
                  <AlertTriangle className="h-4 w-4" />
                  Report This Scam
                </Button>
                <Button
                  variant="outline"
                  onClick={() => navigate('search')}
                  className="rounded-xl"
                >
                  <Search className="h-4 w-4" />
                  Search Database
                </Button>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    </div>
  );
}
