'use client';

import { useState } from 'react';
import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { customerByIdOptions } from '../api/queries';
import { revokeContactShareMutation, shareContactMutation } from '../api/mutations';
import {
  AuditTimeline,
  EmptyState,
  InfoGrid,
  RelatedQuotationList,
  SectionCard,
  TimelineList
} from './shared';
import { formatDate } from '../utils/format';

export function CustomerDetailPage({ id }: { id: string }) {
  const { data } = useSuspenseQuery(customerByIdOptions(id));
  const [targetUserName, setTargetUserName] = useState('');
  const baseShareMutation = shareContactMutation;
  const baseRevokeMutation = revokeContactShareMutation;

  const shareMutation = useMutation({
    ...baseShareMutation,
    onSuccess: async (...args) => {
      await baseShareMutation.onSuccess?.(...args);
      toast.success('แชร์ contact mock สำเร็จ');
      setTargetUserName('');
    }
  });

  const revokeMutation = useMutation({
    ...baseRevokeMutation,
    onSuccess: async (...args) => {
      await baseRevokeMutation.onSuccess?.(...args);
      toast.success('ยกเลิกแชร์ contact mock สำเร็จ');
    }
  });

  const primaryContact = data.contacts.find((contact) => contact.isPrimary) ?? data.contacts[0];

  return (
    <div className='space-y-4'>
      <InfoGrid
        cols={4}
        items={[
          { label: 'Customer Code', value: data.customer.code },
          { label: 'Primary Contact', value: primaryContact?.name ?? '-' },
          { label: 'Branch', value: data.branch.name },
          {
            label: 'Last Activity',
            value: data.auditEvents[0] ? formatDate(data.auditEvents[0].createdAt) : '-'
          }
        ]}
      />

      <Tabs defaultValue='overview' className='space-y-4'>
        <TabsList>
          <TabsTrigger value='overview'>Overview</TabsTrigger>
          <TabsTrigger value='contacts'>Contacts</TabsTrigger>
          <TabsTrigger value='shared'>Shared Contacts</TabsTrigger>
          <TabsTrigger value='enquiries'>Enquiries</TabsTrigger>
          <TabsTrigger value='quotations'>Quotations</TabsTrigger>
          <TabsTrigger value='activity'>Activity Log</TabsTrigger>
        </TabsList>

        <TabsContent value='overview'>
          <SectionCard title='Customer Overview'>
            <InfoGrid
              cols={3}
              items={[
                { label: 'Tax ID', value: data.customer.taxId },
                { label: 'Email', value: data.customer.email },
                { label: 'Phone', value: data.customer.phone },
                {
                  label: 'Address',
                  value: `${data.customer.address}, ${data.customer.subDistrict}`
                },
                { label: 'District', value: data.customer.district },
                { label: 'Province', value: data.customer.province }
              ]}
            />
          </SectionCard>
        </TabsContent>

        <TabsContent value='contacts'>
          <SectionCard title='Customer Contacts'>
            <div className='grid gap-3 md:grid-cols-2'>
              {data.contacts.map((contact) => (
                <div key={contact.id} className='rounded-lg border p-4'>
                  <div className='flex items-center justify-between gap-2'>
                    <p className='font-medium'>{contact.name}</p>
                    {contact.isPrimary ? (
                      <span className='text-primary text-xs'>Primary</span>
                    ) : null}
                  </div>
                  <p className='text-muted-foreground text-sm'>{contact.position}</p>
                  <p className='mt-2 text-sm'>{contact.email}</p>
                  <p className='text-sm'>{contact.phone}</p>
                </div>
              ))}
            </div>
          </SectionCard>
        </TabsContent>

        <TabsContent value='shared'>
          <SectionCard title='Share Contact' description='Mock contact sharing UI'>
            <div className='flex flex-col gap-3 md:flex-row'>
              <Input
                placeholder='ชื่อผู้ใช้ที่ต้องการแชร์'
                value={targetUserName}
                onChange={(event) => setTargetUserName(event.target.value)}
              />
              <Button
                isLoading={shareMutation.isPending}
                onClick={() =>
                  primaryContact &&
                  targetUserName &&
                  shareMutation.mutate({
                    contactId: primaryContact.id,
                    sharedWithUserId: `mock-${targetUserName}`,
                    sharedWithUserName: targetUserName,
                    permission: 'view'
                  })
                }
              >
                แชร์ Contact
              </Button>
            </div>
            <div className='mt-4 space-y-3'>
              {data.shares.length === 0 ? (
                <EmptyState title='ยังไม่มีการแชร์ contact' description='เริ่มจากกรอกชื่อผู้ใช้ด้านบน' />
              ) : (
                data.shares.map((share) => (
                  <div
                    key={share.id}
                    className='flex flex-wrap items-center justify-between gap-3 rounded-lg border p-3'
                  >
                    <div>
                      <p className='font-medium'>{share.sharedWithUserName}</p>
                      <p className='text-muted-foreground text-sm'>
                        Permission: {share.permission}
                      </p>
                    </div>
                    <Button
                      variant='outline'
                      size='sm'
                      isLoading={revokeMutation.isPending}
                      onClick={() =>
                        revokeMutation.mutate({
                          contactId: share.contactId,
                          shareId: share.id
                        })
                      }
                    >
                      Revoke
                    </Button>
                  </div>
                ))
              )}
            </div>
            <div className='mt-6'>
              <TimelineList
                items={data.shareLogs.map((log) => ({
                  id: log.id,
                  title: log.action,
                  detail: `${log.targetUserName} โดย ${log.actorName}`,
                  timestamp: log.createdAt,
                  tone: log.action === 'SHARE' ? 'success' : 'danger'
                }))}
              />
            </div>
          </SectionCard>
        </TabsContent>

        <TabsContent value='enquiries'>
          <SectionCard title='Customer Enquiries'>
            <div className='space-y-3'>
              {data.enquiries.map((enquiry) => (
                <div key={enquiry.id} className='rounded-lg border p-3'>
                  <p className='font-medium'>{enquiry.code}</p>
                  <p className='text-muted-foreground text-sm'>{enquiry.title}</p>
                </div>
              ))}
            </div>
          </SectionCard>
        </TabsContent>

        <TabsContent value='quotations'>
          <RelatedQuotationList quotations={data.quotations} />
        </TabsContent>

        <TabsContent value='activity'>
          <SectionCard title='Activity Log'>
            <AuditTimeline events={data.auditEvents} />
          </SectionCard>
        </TabsContent>
      </Tabs>
    </div>
  );
}
