'use client';

import { useSuspenseQuery } from '@tanstack/react-query';
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Pie,
  PieChart,
  XAxis,
  YAxis
} from 'recharts';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { ChartContainer, ChartTooltip, ChartTooltipContent } from '@/components/ui/chart';
import { crmDashboardQueryOptions } from '../api/queries';
import { KpiCard, QuotationStatusBadge, RelatedQuotationList, SectionCard } from './shared';
import { formatCurrency, formatDate } from '../utils/format';

const chartConfig = {
  primary: { label: 'Primary', color: 'var(--chart-1)' },
  secondary: { label: 'Secondary', color: 'var(--chart-2)' },
  tertiary: { label: 'Tertiary', color: 'var(--chart-3)' }
};

export function CrmDashboardPage() {
  const { data } = useSuspenseQuery(crmDashboardQueryOptions());

  return (
    <div className='space-y-6'>
      <div className='grid gap-4 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-5'>
        {data.metrics.map((metric) => (
          <KpiCard
            key={metric.id}
            label={metric.label}
            value={metric.value}
            change={metric.change}
            trend={metric.trend}
          />
        ))}
      </div>

      <div className='grid gap-4 xl:grid-cols-12'>
        <Card className='xl:col-span-5'>
          <CardHeader>
            <CardTitle>Enquiry Pipeline</CardTitle>
            <CardDescription>สถานะ opportunity ปัจจุบัน</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={chartConfig}>
              <BarChart data={data.enquiryPipeline}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey='label' tickLine={false} axisLine={false} />
                <YAxis allowDecimals={false} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Bar dataKey='value' radius={8} fill='var(--chart-1)' />
              </BarChart>
            </ChartContainer>
          </CardContent>
        </Card>

        <Card className='xl:col-span-4'>
          <CardHeader>
            <CardTitle>Quotation Pipeline</CardTitle>
            <CardDescription>ภาพรวมเอกสารเสนอราคา</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={chartConfig}>
              <PieChart>
                <Pie
                  data={data.quotationPipeline}
                  dataKey='value'
                  nameKey='label'
                  innerRadius={56}
                  outerRadius={92}
                >
                  {data.quotationPipeline.map((entry, index) => (
                    <Cell
                      key={entry.label}
                      fill={
                        [
                          'var(--chart-1)',
                          'var(--chart-2)',
                          'var(--chart-3)',
                          'var(--chart-4)',
                          'var(--chart-5)'
                        ][index % 5]
                      }
                    />
                  ))}
                </Pie>
                <ChartTooltip content={<ChartTooltipContent />} />
              </PieChart>
            </ChartContainer>
          </CardContent>
        </Card>

        <Card className='xl:col-span-3'>
          <CardHeader>
            <CardTitle>Competitor Analysis</CardTitle>
            <CardDescription>คู่แข่งที่เจอบ่อยใน pipeline</CardDescription>
          </CardHeader>
          <CardContent className='space-y-3'>
            {data.competitorAnalysis.map((item) => (
              <div key={item.label} className='space-y-1'>
                <div className='flex items-center justify-between text-sm'>
                  <span>{item.label}</span>
                  <span className='font-medium'>{item.value}</span>
                </div>
                <div className='bg-muted h-2 rounded-full'>
                  <div
                    className='bg-primary h-2 rounded-full'
                    style={{ width: `${(item.value / 4) * 100}%` }}
                  />
                </div>
              </div>
            ))}
          </CardContent>
        </Card>
      </div>

      <div className='grid gap-4 xl:grid-cols-12'>
        <Card className='xl:col-span-6'>
          <CardHeader>
            <CardTitle>Sales Performance</CardTitle>
            <CardDescription>จำนวน quotation และมูลค่าแยกตาม salesperson</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={chartConfig}>
              <BarChart data={data.salesPerformance}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey='label' tickLine={false} axisLine={false} />
                <YAxis allowDecimals={false} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Bar dataKey='value' fill='var(--chart-2)' radius={8} />
              </BarChart>
            </ChartContainer>
          </CardContent>
        </Card>

        <Card className='xl:col-span-6'>
          <CardHeader>
            <CardTitle>Won / Lost Trend</CardTitle>
            <CardDescription>เทียบจำนวนดีลชนะและแพ้รายเดือน</CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={chartConfig}>
              <AreaChart data={data.wonLostTrend}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey='label' tickLine={false} axisLine={false} />
                <YAxis allowDecimals={false} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Area
                  type='monotone'
                  dataKey='value'
                  stroke='var(--chart-1)'
                  fill='var(--chart-1)'
                  fillOpacity={0.2}
                />
                <Area
                  type='monotone'
                  dataKey='secondaryValue'
                  stroke='var(--chart-3)'
                  fill='var(--chart-3)'
                  fillOpacity={0.12}
                />
              </AreaChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </div>

      <div className='grid gap-4 xl:grid-cols-12'>
        <SectionCard
          title='Pending Approvals'
          description='รายการที่ต้องตัดสินใจวันนี้'
          className='xl:col-span-4'
        >
          <div className='space-y-3'>
            {data.pendingApprovals.map((item) => (
              <div key={item.id} className='rounded-lg border p-3'>
                <div className='flex items-center justify-between gap-3'>
                  <p className='font-medium'>{item.quotationCode}</p>
                  <QuotationStatusBadge status='pending_approval' />
                </div>
                <p className='text-muted-foreground mt-1 text-sm'>
                  {item.productType} / Approver Level {item.approverLevel}
                </p>
                <p className='mt-2 text-sm font-medium'>{formatCurrency(item.amount)}</p>
              </div>
            ))}
          </div>
        </SectionCard>

        <SectionCard title='Hot Projects' description='ดีลที่ต้องติดตามใกล้ชิด' className='xl:col-span-5'>
          <RelatedQuotationList quotations={data.hotQuotations} />
        </SectionCard>

        <SectionCard
          title='Follow-ups Due Today'
          description='กิจกรรมติดตามที่ครบกำหนด'
          className='xl:col-span-3'
        >
          <div className='space-y-3'>
            {data.dueFollowUps.map((item) => (
              <div key={item.id} className='rounded-lg border p-3'>
                <p className='font-medium'>{item.title}</p>
                <p className='text-muted-foreground mt-1 text-sm'>Owner: {item.ownerName}</p>
                <p className='text-muted-foreground text-sm'>Due: {formatDate(item.dueDate)}</p>
              </div>
            ))}
          </div>
        </SectionCard>
      </div>
    </div>
  );
}
