'use client';

import Link from 'next/link';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Icons } from '@/components/icons';
import { cn } from '@/lib/utils';
import type {
  ApprovalStep,
  AuditEvent,
  CrmBranch,
  Customer,
  CustomerContact,
  Enquiry,
  Quotation,
  QuotationCustomerRole
} from '../api/types';
import { formatCurrency, formatDate, formatPercent } from '../utils/format';
import {
  getCustomerStatusLabel,
  getEnquiryStatusLabel,
  getQuotationStatusLabel
} from '../utils/status';

export function SectionCard({
  title,
  description,
  action,
  children,
  className
}: {
  title: string;
  description?: string;
  action?: React.ReactNode;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <Card className={className}>
      <CardHeader className='flex flex-row items-start justify-between space-y-0'>
        <div className='space-y-1'>
          <CardTitle className='text-base'>{title}</CardTitle>
          {description ? <CardDescription>{description}</CardDescription> : null}
        </div>
        {action}
      </CardHeader>
      <CardContent>{children}</CardContent>
    </Card>
  );
}

export function KpiCard({
  label,
  value,
  change,
  trend
}: {
  label: string;
  value: string;
  change: string;
  trend: 'up' | 'down' | 'flat';
}) {
  const TrendIcon =
    trend === 'up' ? Icons.trendingUp : trend === 'down' ? Icons.trendingDown : Icons.clock;

  return (
    <Card className='bg-gradient-to-br from-card via-card to-muted/40'>
      <CardHeader className='pb-3'>
        <div className='flex items-start justify-between gap-3'>
          <CardDescription>{label}</CardDescription>
          <Badge variant='outline'>
            <TrendIcon className='mr-1 h-3.5 w-3.5' />
            {change}
          </Badge>
        </div>
        <CardTitle className='text-2xl'>{value}</CardTitle>
      </CardHeader>
    </Card>
  );
}

export function BranchBadge({ branch }: { branch: CrmBranch }) {
  return <Badge variant='secondary'>{branch.code}</Badge>;
}

export function CustomerStatusBadge({ status }: { status: Customer['customerStatus'] }) {
  return (
    <Badge
      variant={
        status === 'inactive' ? 'destructive' : status === 'prospect' ? 'outline' : 'secondary'
      }
    >
      {getCustomerStatusLabel(status)}
    </Badge>
  );
}

export function EnquiryStatusBadge({ status }: { status: Enquiry['status'] }) {
  return (
    <Badge
      variant={
        status === 'cancelled' || status === 'closed_lost'
          ? 'destructive'
          : status === 'converted'
            ? 'secondary'
            : 'outline'
      }
    >
      {getEnquiryStatusLabel(status)}
    </Badge>
  );
}

export function QuotationStatusBadge({ status }: { status: Quotation['status'] }) {
  return (
    <Badge
      variant={
        status === 'accepted' || status === 'approved'
          ? 'secondary'
          : status === 'lost' || status === 'rejected' || status === 'cancelled'
            ? 'destructive'
            : 'outline'
      }
    >
      {getQuotationStatusLabel(status)}
    </Badge>
  );
}

export function InfoGrid({
  items,
  cols = 2
}: {
  items: Array<{ label: string; value: React.ReactNode }>;
  cols?: 2 | 3 | 4;
}) {
  return (
    <div
      className={cn(
        'grid gap-4',
        cols === 2 && 'md:grid-cols-2',
        cols === 3 && 'md:grid-cols-3',
        cols === 4 && 'md:grid-cols-2 xl:grid-cols-4'
      )}
    >
      {items.map((item) => (
        <div key={item.label} className='rounded-lg border bg-muted/20 p-3'>
          <p className='text-muted-foreground text-xs uppercase tracking-[0.18em]'>{item.label}</p>
          <div className='mt-1 text-sm font-medium'>{item.value}</div>
        </div>
      ))}
    </div>
  );
}

export function TimelineList({
  items
}: {
  items: Array<{
    id: string;
    title: string;
    detail: string;
    actorName?: string;
    timestamp: string;
    tone?: 'default' | 'success' | 'danger';
  }>;
}) {
  return (
    <div className='space-y-3'>
      {items.map((item) => (
        <div key={item.id} className='flex gap-3'>
          <div className='mt-1 flex flex-col items-center'>
            <span
              className={cn(
                'inline-flex h-2.5 w-2.5 rounded-full bg-primary',
                item.tone === 'success' && 'bg-emerald-500',
                item.tone === 'danger' && 'bg-destructive'
              )}
            />
            <span className='bg-border mt-1 h-full w-px' />
          </div>
          <div className='pb-3'>
            <div className='flex flex-wrap items-center gap-2'>
              <p className='text-sm font-medium'>{item.title}</p>
              <p className='text-muted-foreground text-xs'>{formatDate(item.timestamp)}</p>
            </div>
            <p className='text-muted-foreground text-sm'>{item.detail}</p>
            {item.actorName ? <p className='mt-1 text-xs'>โดย {item.actorName}</p> : null}
          </div>
        </div>
      ))}
    </div>
  );
}

export function CustomerRoleCards({
  roles,
  customers,
  contacts
}: {
  roles: QuotationCustomerRole[];
  customers: Customer[];
  contacts: CustomerContact[];
}) {
  return (
    <div className='grid gap-3 md:grid-cols-2 xl:grid-cols-4'>
      {roles.map((role) => {
        const customer = customers.find((item) => item.id === role.customerId);
        const contact = contacts.find((item) => item.id === role.contactId);

        return (
          <div
            key={`${role.role}-${role.customerId}`}
            className='rounded-lg border bg-muted/20 p-4'
          >
            <div className='flex items-center justify-between gap-3'>
              <p className='text-sm font-semibold capitalize'>{role.role}</p>
              <Badge variant='outline'>{customer?.code}</Badge>
            </div>
            <p className='mt-2 text-sm font-medium'>{customer?.name}</p>
            <p className='text-muted-foreground text-sm'>{contact?.name ?? 'No contact'}</p>
            <p className='text-muted-foreground text-xs'>{contact?.position}</p>
          </div>
        );
      })}
    </div>
  );
}

export function QuotationPreviewPanel({
  quotation,
  ownerCustomer,
  ownerContact,
  approvalSteps
}: {
  quotation: Quotation;
  ownerCustomer?: Customer;
  ownerContact?: CustomerContact;
  approvalSteps: ApprovalStep[];
}) {
  return (
    <SectionCard
      title='Quotation Preview'
      description='Mock preview พร้อมต่อยอดไป pdfme/template mapping'
    >
      <div className='rounded-xl border bg-background p-5 shadow-sm'>
        <div className='flex flex-wrap items-start justify-between gap-4 border-b pb-4'>
          <div>
            <p className='text-primary text-xs uppercase tracking-[0.3em]'>ALLA OS CRM vNext</p>
            <h3 className='mt-2 text-xl font-semibold'>{quotation.code}</h3>
            <p className='text-muted-foreground text-sm'>{quotation.project}</p>
          </div>
          <div className='space-y-1 text-sm'>
            <p>
              <span className='text-muted-foreground'>quotation_date:</span>{' '}
              {quotation.quotationDate}
            </p>
            <p>
              <span className='text-muted-foreground'>valid_until:</span> {quotation.validUntil}
            </p>
            <p>
              <span className='text-muted-foreground'>currency:</span> THB
            </p>
          </div>
        </div>

        <div className='grid gap-4 py-4 md:grid-cols-2'>
          <div className='space-y-1 text-sm'>
            <p className='font-medium'>customer_name</p>
            <p>{ownerCustomer?.name}</p>
            <p className='text-muted-foreground'>{ownerCustomer?.address}</p>
            <p className='text-muted-foreground'>{ownerCustomer?.phone}</p>
            <p className='text-muted-foreground'>{ownerCustomer?.email}</p>
          </div>
          <div className='space-y-1 text-sm'>
            <p className='font-medium'>customer_att</p>
            <p>{ownerContact?.name ?? '-'}</p>
            <p className='text-muted-foreground'>{ownerContact?.position ?? '-'}</p>
            <p className='text-muted-foreground'>{quotation.siteLocation}</p>
          </div>
        </div>

        <div className='space-y-3 border-t pt-4'>
          <div>
            <p className='text-sm font-medium'>item_topic</p>
            <div className='mt-2 space-y-2'>
              {quotation.items.map((item) => (
                <div
                  key={item.id}
                  className='flex items-center justify-between gap-4 rounded-lg border p-3 text-sm'
                >
                  <div>
                    <p className='font-medium'>{item.description}</p>
                    <p className='text-muted-foreground'>
                      {item.quantity} {item.unit} x {formatCurrency(item.unitPrice)}
                    </p>
                  </div>
                  <p className='font-semibold'>{formatCurrency(item.amount)}</p>
                </div>
              ))}
            </div>
          </div>
          <div className='rounded-lg bg-muted/30 p-3 text-sm'>
            <p className='font-medium'>exclusion_data</p>
            <ul className='text-muted-foreground mt-1 space-y-1'>
              {quotation.topics
                .find((topic) => topic.type === 'exclusion')
                ?.items.map((item) => (
                  <li key={item}>- {item}</li>
                ))}
            </ul>
          </div>
          <div className='flex items-center justify-between rounded-lg border border-dashed p-3 text-sm'>
            <p className='font-medium'>quotation_price</p>
            <p className='text-lg font-semibold'>{formatCurrency(quotation.totalAmount)}</p>
          </div>
          <div className='rounded-lg bg-muted/30 p-3 text-sm'>
            <p className='font-medium'>approver names and positions</p>
            <ul className='text-muted-foreground mt-1 space-y-1'>
              {approvalSteps.map((step) => (
                <li key={step.id}>
                  {step.approverName} / {step.approverPosition}
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </SectionCard>
  );
}

export function RelatedQuotationList({ quotations }: { quotations: Quotation[] }) {
  return (
    <div className='space-y-3'>
      {quotations.map((quotation) => (
        <div
          key={quotation.id}
          className='flex flex-wrap items-center justify-between gap-3 rounded-lg border p-3'
        >
          <div>
            <div className='flex items-center gap-2'>
              <p className='font-medium'>{quotation.code}</p>
              <QuotationStatusBadge status={quotation.status} />
            </div>
            <p className='text-muted-foreground text-sm'>{quotation.project}</p>
          </div>
          <div className='flex items-center gap-3'>
            <p className='text-sm font-medium'>{formatCurrency(quotation.totalAmount)}</p>
            <Button variant='outline' asChild size='sm'>
              <Link href={`/dashboard/crm-demo/quotations/${quotation.id}`}>
                <Icons.arrowRight className='mr-1 h-4 w-4' />
                เปิด
              </Link>
            </Button>
          </div>
        </div>
      ))}
    </div>
  );
}

export function HotProjectPill({ active }: { active: boolean }) {
  return active ? <Badge>Hot</Badge> : <Badge variant='outline'>Normal</Badge>;
}

export function ChancePill({ value }: { value: number }) {
  return <Badge variant='outline'>{formatPercent(value)}</Badge>;
}

export function AuditTimeline({ events }: { events: AuditEvent[] }) {
  return (
    <TimelineList
      items={events.map((event) => ({
        id: event.id,
        title: event.action,
        detail: event.detail,
        actorName: event.actorName,
        timestamp: event.createdAt,
        tone:
          event.action === 'APPROVE' ? 'success' : event.action === 'REJECT' ? 'danger' : 'default'
      }))}
    />
  );
}

export function EmptyState({ title, description }: { title: string; description: string }) {
  return (
    <div className='rounded-lg border border-dashed p-8 text-center'>
      <p className='font-medium'>{title}</p>
      <p className='text-muted-foreground mt-1 text-sm'>{description}</p>
    </div>
  );
}
