'use client';

import Link from 'next/link';
import { useMemo, useState } from 'react';
import { useSuspenseQuery } from '@tanstack/react-query';
import { Icons } from '@/components/icons';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { formatDate, formatDateTime } from '@/lib/date-format';
import { formatNumber } from '@/lib/number-format';
import type {
  QuotationReferenceData,
  QuotationRelationItem
} from '@/features/crm/quotations/api/types';
import { QuotationFormSheet } from '@/features/crm/quotations/components/quotation-form-sheet';
import { getPipelineStageThaiLabel } from '@/features/crm/shared/terminology';
import { opportunityByIdOptions, opportunityProjectPartiesOptions } from '../api/queries';
import type { OpportunityRecord, OpportunityReferenceData } from '../api/types';
import { OpportunityAssignmentDialog } from './opportunity-assignment-dialog';
import { OpportunityFollowupsTab } from './opportunity-followups-tab';
import { OpportunityFormSheet } from './opportunity-form-sheet';
import { OpportunityOutcomeCard } from './opportunity-outcome-card';
import { OpportunityStatusBadge } from './opportunity-status-badge';
import { QuotationReadinessPanel } from './quotation-readiness-panel';
import { SourceLeadCard, type SourceLeadSummary } from './source-lead-card';

function FieldItem({ label, value }: { label: string; value: string | null | undefined }) {
  return (
    <div className='space-y-1'>
      <div className='text-muted-foreground text-xs'>{label}</div>
      <div className='text-sm'>{value || '-'}</div>
    </div>
  );
}

function getPipelineStageLabel(stage: OpportunityRecord['pipelineStage']) {
  return getPipelineStageThaiLabel(stage);
}

interface OpportunityDetailProps {
  opportunityId: string;
  referenceData: OpportunityReferenceData;
  relatedQuotations: QuotationRelationItem[];
  workspace: 'lead' | 'opportunity';
  canUpdate: boolean;
  canAssign: boolean;
  canReassign: boolean;
  canViewRelatedQuotations: boolean;
  canViewOutcomeCommercialData: boolean;
  canMarkWon: boolean;
  canMarkLost: boolean;
  canReopen: boolean;
  canCreateQuotation: boolean;
  canManageFollowups: {
    create: boolean;
    update: boolean;
    delete: boolean;
  };
  sourceLead?: SourceLeadSummary | null;
  quotationReferenceData?: QuotationReferenceData | null;
}

export function OpportunityDetail({
  opportunityId,
  referenceData,
  relatedQuotations,
  workspace,
  canUpdate,
  canAssign,
  canReassign,
  canViewRelatedQuotations,
  canViewOutcomeCommercialData,
  canMarkWon,
  canMarkLost,
  canReopen,
  canCreateQuotation,
  canManageFollowups,
  sourceLead = null,
  quotationReferenceData = null
}: OpportunityDetailProps) {
  const { data } = useSuspenseQuery(opportunityByIdOptions(opportunityId));
  const { data: projectPartiesData } = useSuspenseQuery(
    opportunityProjectPartiesOptions(opportunityId)
  );
  const [editOpen, setEditOpen] = useState(false);
  const [assignmentOpen, setAssignmentOpen] = useState(false);
  const [quotationOpen, setQuotationOpen] = useState(false);
  const opportunity = data.opportunity;

  const branchMap = useMemo(
    () => new Map(referenceData.branches.map((item) => [item.id, item.name])),
    [referenceData]
  );
  const customerMap = useMemo(
    () => new Map(referenceData.customers.map((item) => [item.id, item])),
    [referenceData]
  );
  const contactMap = useMemo(
    () => new Map(referenceData.contacts.map((item) => [item.id, item])),
    [referenceData]
  );
  const statusMap = useMemo(
    () => new Map(referenceData.statuses.map((item) => [item.id, item])),
    [referenceData]
  );
  const productTypeMap = useMemo(
    () => new Map(referenceData.productTypes.map((item) => [item.id, item.label])),
    [referenceData]
  );
  const priorityMap = useMemo(
    () => new Map(referenceData.priorities.map((item) => [item.id, item.label])),
    [referenceData]
  );

  const customer = customerMap.get(opportunity.customerId);
  const contact = opportunity.contactId ? contactMap.get(opportunity.contactId) : null;
  const status = statusMap.get(opportunity.status);
  const pipelineStageLabel = getPipelineStageLabel(opportunity.pipelineStage);
  const canManageAssignment = opportunity.assignedToUserId ? canReassign : canAssign;
  const assignmentMode = opportunity.assignedToUserId ? 'reassign' : 'assign';

  return (
    <div className='space-y-6'>
      <OpportunityFormSheet
        open={editOpen}
        onOpenChange={setEditOpen}
        referenceData={referenceData}
        workspace={workspace}
        opportunity={opportunity}
      />
      <OpportunityAssignmentDialog
        opportunity={opportunity}
        referenceData={referenceData}
        mode={assignmentMode}
        open={assignmentOpen}
        onOpenChange={setAssignmentOpen}
      />
      {quotationReferenceData ? (
        <QuotationFormSheet
          open={quotationOpen}
          onOpenChange={setQuotationOpen}
          referenceData={quotationReferenceData}
        />
      ) : null}

      <div className='flex items-start justify-between gap-4'>
        <div>
          <div className='flex items-center gap-3'>
            <h2 className='text-2xl font-semibold'>{opportunity.code}</h2>
            <OpportunityStatusBadge
              code={status?.code}
              label={status?.label ?? opportunity.status}
            />
          </div>
          <p className='text-muted-foreground mt-2 text-sm'>
            Opportunity detail for sales execution, follow-up continuity, and quotation readiness.
          </p>
        </div>

        <div className='flex flex-wrap gap-2'>
          {canCreateQuotation ? (
            <Button onClick={() => setQuotationOpen(true)}>
              <Icons.add className='mr-2 h-4 w-4' />
              Create Quotation
            </Button>
          ) : null}
          {sourceLead ? (
            <Button variant='outline' asChild>
              <Link href={`/dashboard/crm/leads/${sourceLead.id}`}>Open Source Lead</Link>
            </Button>
          ) : null}
          {canManageAssignment ? (
            <Button variant='outline' onClick={() => setAssignmentOpen(true)}>
              {assignmentMode === 'assign' ? 'Assign Opportunity' : 'Reassign Opportunity'}
            </Button>
          ) : null}
          {canUpdate ? (
            <Button variant='outline' onClick={() => setEditOpen(true)}>
              Edit Opportunity
            </Button>
          ) : null}
        </div>
      </div>

      <div className='grid gap-6 xl:grid-cols-3'>
        <div className='space-y-6 xl:col-span-2'>
          <Card>
            <CardHeader>
              <CardTitle>Opportunity Summary</CardTitle>
              <CardDescription>Core sales execution snapshot for this opportunity.</CardDescription>
            </CardHeader>
            <CardContent className='grid gap-4 md:grid-cols-2 xl:grid-cols-3'>
              <FieldItem label='Customer' value={customer?.name} />
              <FieldItem label='Contact' value={contact?.name} />
              <FieldItem label='Project Name' value={opportunity.projectName} />
              <FieldItem label='Project Location' value={opportunity.projectLocation} />
              <FieldItem label='Pipeline Stage' value={pipelineStageLabel} />
              <FieldItem label='Sales Owner' value={opportunity.assignedToName} />
              <FieldItem label='Status' value={status?.label ?? opportunity.status} />
              <FieldItem
                label='Expected Close Date'
                value={
                  opportunity.expectedCloseDate
                    ? formatDate(opportunity.expectedCloseDate)
                    : null
                }
              />
              <FieldItem
                label='Estimated Value'
                value={
                  opportunity.estimatedValue !== null
                    ? formatNumber(opportunity.estimatedValue)
                    : null
                }
              />
            </CardContent>
          </Card>

          <SourceLeadCard sourceLead={sourceLead} />

          <Card>
            <CardHeader>
              <CardTitle>Customer / Contact</CardTitle>
            </CardHeader>
            <CardContent className='grid gap-4 md:grid-cols-2'>
              <FieldItem label='Customer Code' value={customer?.code} />
              <FieldItem label='Customer Owner' value={customer?.ownerName} />
              <FieldItem label='Contact Name' value={contact?.name} />
              <FieldItem label='Contact Email' value={contact?.email} />
              <FieldItem label='Contact Mobile' value={contact?.mobile} />
              <FieldItem
                label='Branch'
                value={opportunity.branchId ? branchMap.get(opportunity.branchId) : null}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Requirement</CardTitle>
            </CardHeader>
            <CardContent className='space-y-4'>
              <FieldItem label='Title' value={opportunity.title} />
              <FieldItem label='Description' value={opportunity.description} />
              <FieldItem label='Requirement' value={opportunity.requirement} />
              <div className='grid gap-4 md:grid-cols-2'>
                <FieldItem label='Source' value={opportunity.source} />
                <FieldItem label='Assignment Remark' value={opportunity.assignmentRemark} />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Sales Qualification</CardTitle>
            </CardHeader>
            <CardContent className='grid gap-4 md:grid-cols-2 xl:grid-cols-3'>
              <FieldItem
                label='Product Type'
                value={productTypeMap.get(opportunity.productType) ?? opportunity.productType}
              />
              <FieldItem
                label='Priority'
                value={priorityMap.get(opportunity.priority) ?? opportunity.priority}
              />
              <FieldItem
                label='Chance %'
                value={opportunity.chancePercent !== null ? `${opportunity.chancePercent}%` : null}
              />
              <FieldItem label='Competitor' value={opportunity.competitor} />
              <FieldItem
                label='Assigned At'
                value={
                  opportunity.assignedAt ? formatDateTime(opportunity.assignedAt) : null
                }
              />
              <FieldItem label='Assigned By' value={opportunity.assignedByName} />
            </CardContent>
          </Card>

          <Tabs defaultValue='followups' className='space-y-4'>
            <TabsList>
              <TabsTrigger value='followups'>Follow-up Timeline</TabsTrigger>
              <TabsTrigger value='quotations'>Linked Quotations</TabsTrigger>
              <TabsTrigger value='activity'>Activity</TabsTrigger>
            </TabsList>

            <TabsContent value='followups'>
              <OpportunityFollowupsTab
                opportunityId={opportunityId}
                customerId={opportunity.customerId}
                referenceData={referenceData}
                canCreate={canManageFollowups.create}
                canUpdate={canManageFollowups.update}
                canDelete={canManageFollowups.delete}
              />
            </TabsContent>

            <TabsContent value='quotations'>
              <Card>
                <CardHeader>
                  <CardTitle>Linked Quotations</CardTitle>
                </CardHeader>
                <CardContent className='space-y-3'>
                  {!canViewRelatedQuotations ? (
                    <div className='text-muted-foreground text-sm'>
                      Quotation access is restricted.
                    </div>
                  ) : relatedQuotations.length === 0 ? (
                    <div className='text-muted-foreground text-sm'>No quotations created yet.</div>
                  ) : (
                    relatedQuotations.map((quotation) => (
                      <div key={quotation.id} className='border-border rounded-md border p-3'>
                        <div className='flex items-center justify-between gap-3'>
                          <Link
                            href={`/dashboard/crm/quotations/${quotation.id}`}
                            className='font-medium hover:underline'
                          >
                            {quotation.code}
                          </Link>
                          <Badge variant='outline'>{quotation.status}</Badge>
                        </div>
                        <div className='mt-1 text-sm'>{quotation.quotationType}</div>
                      </div>
                    ))
                  )}
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value='activity'>
              <Card>
                <CardHeader>
                  <CardTitle>Activity</CardTitle>
                </CardHeader>
                <CardContent className='space-y-3'>
                  {data.activity.length === 0 ? (
                    <div className='text-muted-foreground text-sm'>No activity yet.</div>
                  ) : (
                    data.activity.map((activity) => (
                      <div key={activity.id} className='border-border rounded-md border p-3'>
                        <div className='font-medium'>{activity.action}</div>
                        <div className='text-muted-foreground mt-1 text-xs'>
                          {activity.actorName ?? activity.userId} -{' '}
                          {formatDateTime(activity.createdAt)}
                        </div>
                      </div>
                    ))
                  )}
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>

        <div className='space-y-6'>
          <QuotationReadinessPanel opportunity={opportunity} />

          <OpportunityOutcomeCard
            opportunityId={opportunityId}
            referenceData={referenceData}
            canViewCommercialData={canViewOutcomeCommercialData}
            canMarkWon={canMarkWon}
            canMarkLost={canMarkLost}
            canReopen={canReopen}
          />

          <Card>
            <CardHeader>
              <CardTitle>Quotation Context</CardTitle>
            </CardHeader>
            <CardContent className='space-y-3'>
              <FieldItem label='Related Quotations' value={String(relatedQuotations.length)} />
              <FieldItem label='Project Parties' value={String(projectPartiesData.items.length)} />
              <FieldItem
                label='Record Type'
                value={workspace === 'opportunity' ? 'Opportunity' : 'Lead'}
              />
              {relatedQuotations.length ? (
                <div className='space-y-2'>
                  {relatedQuotations.slice(0, 3).map((quotation) => (
                    <div key={quotation.id} className='rounded-lg border p-3 text-sm'>
                      <div className='flex items-center justify-between gap-3'>
                        <Link
                          href={`/dashboard/crm/quotations/${quotation.id}`}
                          className='font-medium hover:underline'
                        >
                          {quotation.code}
                        </Link>
                        <Badge variant='outline'>Rev {quotation.revision}</Badge>
                      </div>
                      <div className='text-muted-foreground mt-1'>
                        {quotation.status} · {formatNumber(quotation.totalAmount)}{' '}
                        {quotation.currency}
                      </div>
                    </div>
                  ))}
                </div>
              ) : null}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
