import React from 'react';
import { base44 } from '@/api/base44Client';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { Helmet } from 'react-helmet-async';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { AlertTriangle, FileWarning, AlertCircle, ArrowRight, Phone } from 'lucide-react';
import { getCanonicalSlug } from '@/lib/getCanonicalSlug';

const severityStyles = {
  Critical: 'bg-accent/10 text-accent border-accent/20',
  High: 'bg-orange-500/10 text-orange-600 border-orange-500/20',
  Medium: 'bg-yellow-500/10 text-yellow-600 border-yellow-500/20',
  Low: 'bg-green-500/10 text-green-600 border-green-500/20',
};

const severityIcons = {
  Critical: AlertTriangle,
  High: FileWarning,
  Medium: AlertCircle,
  Low: AlertCircle,
};

// Categorize notices by keyword matching on notice_code — resilient to exact-code mismatches
function categorizeNotice(notice) {
  const code = (notice.notice_code || '').toUpperCase();
  const slug = (notice.slug || '').toLowerCase();
  if (code.includes('668') || code.includes('LETTER 1058') || code.includes('LETTER 11') || 
      code.includes('CP504') || code.includes('CP90') || slug.includes('levy') || slug.includes('garnish')) {
    return 'Levy & Enforcement';
  }
  if (code.includes('CP2000') || code.includes('CP2501') || code.includes('CP14') || 
      code.includes('CP297') || slug.includes('assessment') || slug.includes('adjustment') || slug.includes('underreport')) {
    return 'Assessment & Adjustment';
  }
  if (code.includes('CP521') || code.includes('CP523') || code.includes('CP32A') || 
      code.includes('CP71C') || code.includes('CP501') || code.includes('CP502') || code.includes('CP503') ||
      slug.includes('balance') || slug.includes('payment') || slug.includes('installment')) {
    return 'Balance Due & Payment';
  }
  if (code.includes('3172') || slug.includes('lien') || slug.includes('property')) {
    return 'Lien & Property';
  }
  return 'Other Notices';
}

export default function NoticesHub() {
  const { data: notices } = useQuery({
    queryKey: ['irs-notices'],
    queryFn: () => base44.entities.IrsNotice.list(),
    initialData: [],
  });

  // Deduplicate: only show one record per canonical slug
  const seenSlugs = new Set();
  const deduped = notices.filter(n => {
    const cs = getCanonicalSlug(n);
    if (seenSlugs.has(cs)) return false;
    seenSlugs.add(cs);
    return true;
  });

  const criticalNotices = deduped.filter(n => n.severity_level === 'Critical').slice(0, 6);
  
  // Dynamically organize ALL notices by category using resilient keyword matching
  const categoryOrder = ['Levy & Enforcement', 'Assessment & Adjustment', 'Balance Due & Payment', 'Lien & Property', 'Other Notices'];
  const allNoticesByCategory = categoryOrder.reduce((acc, cat) => {
    const catNotices = deduped.filter(n => categorizeNotice(n) === cat);
    if (catNotices.length > 0) acc[cat] = catNotices;
    return acc;
  }, {});

  const faqItems = [
    { q: 'What is an IRS notice?', a: 'An official communication from the IRS regarding your tax account.' },
    { q: 'How long do I have to respond?', a: 'Response deadlines vary by notice type, typically 30-60 days.' },
    { q: 'What if I disagree with a notice?', a: 'You have appeal rights; consult a tax professional immediately.' },
    { q: 'Can a levy be stopped?', a: 'Yes, with immediate professional intervention and proper documentation.' },
  ];

  return (
    <>
      <Helmet>
        <title>IRS Notices Explained: CP2000, CP504, CP668, CP90 & More | TaxNotices.ai</title>
        <meta name="description" content="Complete IRS notices guide: CP2000 income mismatches, CP504/CP668 levy notices, CP90 deficiency, and all other notice types. Learn deadlines, penalties, and response options." />
        <link rel="canonical" href="https://taxnotices.ai/notices" />
        <meta property="og:title" content="IRS Notices Directory & Response Guide | TaxNotices.ai" />
        <meta property="og:description" content="Understand any IRS notice: CP2000, CP504, levy, lien, assessment. Get deadlines and next steps instantly." />
      </Helmet>

      <div className="min-h-screen bg-background">
        {/* Hero */}
        <div className="bg-primary/5 border-b border-border py-14 sm:py-18">
          <div className="max-w-4xl mx-auto px-4 sm:px-6">
            <h1 className="font-serif text-4xl sm:text-5xl font-bold text-foreground mb-3">
              IRS Notices Explained in Plain English
            </h1>
            <p className="text-lg text-muted-foreground max-w-2xl mb-2">
              Received an IRS notice? We translate complex IRS jargon into plain English in seconds.
            </p>
            <p className="text-base text-muted-foreground max-w-2xl mb-8">
              Learn what your notice means, your response deadline, and what actions to take immediately.
            </p>

            <a href="tel:+18448296684">
              <Button className="bg-accent hover:bg-accent/90 text-white gap-2 font-semibold">
                <Phone className="w-4 h-4" />
                Speak with a Tax Specialist
              </Button>
            </a>
          </div>
        </div>

        <div className="max-w-4xl mx-auto px-4 sm:px-6 py-12">
          {/* Breadcrumb */}
          <div className="mb-8 text-xs text-muted-foreground flex gap-2 items-center">
            <span>Notices</span>
            <span>•</span>
            <Link to="/guides" className="text-primary hover:text-accent">Resolution Strategies</Link>
          </div>

          {/* Section 1: What This Category Covers */}
          <section className="mb-12">
            <h2 className="text-2xl font-bold text-foreground mb-4">What Each Notice Means</h2>
            <p className="text-muted-foreground mb-4">
              IRS notices include levy warnings, assessment notifications, lien filings, payment plan defaults, and more. Each notice has specific meaning, legal implications, and response deadlines. This hub covers all notice types with severity levels, plain-English explanations, and next-step guidance.
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Card>
                <CardContent className="p-5">
                  <h3 className="font-semibold text-foreground mb-2">Levy & Enforcement Notices</h3>
                  <p className="text-sm text-muted-foreground">CP504, CP668-Y/W, and related enforcement actions.</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="p-5">
                  <h3 className="font-semibold text-foreground mb-2">Assessment Notices</h3>
                  <p className="text-sm text-muted-foreground">CP90, CP14, CP3219 and other assessment notifications.</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="p-5">
                  <h3 className="font-semibold text-foreground mb-2">Payment Plan Issues</h3>
                  <p className="text-sm text-muted-foreground">CP523 defaults and payment arrangement changes.</p>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="p-5">
                  <h3 className="font-semibold text-foreground mb-2">Lien & Property Notices</h3>
                  <p className="text-sm text-muted-foreground">Letter 3172, Notice of Federal Tax Lien.</p>
                </CardContent>
              </Card>
            </div>
          </section>

          {/* Authority & Freshness Signals */}
          <div className="mb-10 text-xs text-muted-foreground flex gap-4 items-center">
            <span>Last updated: May 2026</span>
            <span>•</span>
            <span>Reviewed for accuracy against IRS.gov guidelines</span>
          </div>

          {/* Section 2: Most Common Questions */}
          <section className="mb-12">
            <h2 className="text-2xl font-bold text-foreground mb-6">Most Common Questions</h2>
            <div className="space-y-4">
              {faqItems.map((item, i) => (
                <div key={i} className="border border-border rounded-lg p-5 hover:bg-secondary/30 transition-colors">
                  <h3 className="font-semibold text-foreground mb-2">{item.q}</h3>
                  <p className="text-sm text-muted-foreground">{item.a}</p>
                </div>
              ))}
            </div>
          </section>

          {/* Section 3: Top Critical Notices */}
          <section className="mb-12">
            <h2 className="text-2xl font-bold text-foreground mb-4">Urgent: Critical Notices</h2>
            <p className="text-muted-foreground mb-6">These require immediate action:</p>
            {criticalNotices.length === 0 && (
              <p className="text-sm text-muted-foreground">Loading notices...</p>
            )}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {criticalNotices.map(notice => {
                const Icon = severityIcons[notice.severity_level] || AlertCircle;
                return (
                  <Link key={notice.id} to={`/notices/${getCanonicalSlug(notice)}`}>
                    <Card className="h-full hover:shadow-md hover:border-accent/20 transition-all cursor-pointer group">
                      <CardContent className="p-5">
                        <div className="flex items-start justify-between mb-3">
                          <Icon className="w-5 h-5 text-accent" />
                          <Badge className="bg-accent/10 text-accent border-accent/20">{notice.severity_level}</Badge>
                        </div>
                        <h3 className="font-semibold text-lg text-foreground group-hover:text-accent transition-colors">
                          {notice.notice_code}
                        </h3>
                        <p className="text-sm text-muted-foreground mt-1">{notice.common_name}</p>
                        <div className="mt-4 flex items-center gap-1.5 text-xs font-medium text-primary group-hover:text-accent transition-colors">
                          Learn more <ArrowRight className="w-3 h-3" />
                        </div>
                      </CardContent>
                    </Card>
                  </Link>
                );
              })}
            </div>
          </section>

          {/* Section 4: All Notices by Type */}
          <section className="mb-12">
            <h2 className="text-2xl font-bold text-foreground mb-6">Browse All Notices</h2>

            {Object.entries(allNoticesByCategory).map(([categoryName, categoryNotices]) => (
              <div key={categoryName} className="mb-8">
                <h3 className="text-lg font-semibold text-foreground mb-4 flex items-center gap-2">
                  {categoryName === 'Levy & Enforcement' && <AlertTriangle className="w-5 h-5 text-accent" />}
                  {categoryName}
                </h3>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {categoryNotices.map(notice => (
                    <Link key={notice.id} to={`/notices/${getCanonicalSlug(notice)}`}>
                      <Card className="hover:bg-secondary/50 transition-all cursor-pointer group">
                        <CardContent className="p-4 flex items-start justify-between">
                          <div>
                            <span className="font-mono text-sm font-semibold text-primary">{notice.notice_code}</span>
                            <p className="text-sm text-muted-foreground mt-1">{notice.common_name}</p>
                          </div>
                          <Badge variant="outline" className={`text-xs flex-shrink-0 ml-2 ${severityStyles[notice.severity_level] || ''}`}>
                            {notice.severity_level}
                          </Badge>
                        </CardContent>
                      </Card>
                    </Link>
                  ))}
                </div>
              </div>
            ))}
          </section>

          {/* Section 5: Related Hubs */}
          <section>
            <h2 className="text-2xl font-bold text-foreground mb-6">Related Hubs</h2>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              <Link to="/tax-codes">
                <Card className="h-full hover:shadow-md hover:border-primary/30 transition-all cursor-pointer">
                  <CardContent className="p-5">
                    <h3 className="font-semibold text-foreground">Tax Code Library</h3>
                    <p className="text-sm text-muted-foreground mt-2">Understand the IRC sections behind each notice.</p>
                  </CardContent>
                </Card>
              </Link>
              <Link to="/guides">
                <Card className="h-full hover:shadow-md hover:border-primary/30 transition-all cursor-pointer">
                  <CardContent className="p-5">
                    <h3 className="font-semibold text-foreground">Resolution Guides</h3>
                    <p className="text-sm text-muted-foreground mt-2">Step-by-step guides for levy release and payment plans.</p>
                  </CardContent>
                </Card>
              </Link>
              <Link to="/faq">
                <Card className="h-full hover:shadow-md hover:border-primary/30 transition-all cursor-pointer">
                  <CardContent className="p-5">
                    <h3 className="font-semibold text-foreground">FAQ</h3>
                    <p className="text-sm text-muted-foreground mt-2">Answers to frequently asked questions about IRS notices.</p>
                  </CardContent>
                </Card>
              </Link>
            </div>
          </section>
        </div>
      </div>
    </>
  );
}