'use client';

import * as React from 'react';
import { useParams, useRouter } from 'next/navigation';
import { CustomerRegistration } from '@/network/apis/dashboard/customers-registrations/type';
import axios from '@/network/axios';
import { apis } from '@/utils/apis/apis';
import { SuccessResponse } from '@/utils/types/Responses';
import { RiErrorWarningFill } from '@remixicon/react';
import { useQuery } from '@tanstack/react-query';
import { Alert, AlertIcon, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import CustomerDeleteDialog from '../customerDeleteDialog/CustomerDeleteDialog';

function Row({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <div className="grid grid-cols-12 gap-3 py-2 border-b last:border-b-0">
      <div className="col-span-4 md:col-span-3 text-slate-500 text-sm">
        {label}
      </div>
      <div className="col-span-8 md:col-span-9 text-sm">{children}</div>
    </div>
  );
}

export const fetchCustomerRegistrationDetailsById = async (id: string) => {
  const response = await axios.get<SuccessResponse<CustomerRegistration>>(
    apis.DASHBOARD.CUSTOMERS_REGISTRATIONS.DETAILS(id),
  );
  return response.data?.data;
};

export default function CustomerRegistrationDetails() {
  const router = useRouter();
  const params = useParams();
  const id = params?.id ? String(params.id) : undefined;
  const [isDeleteOpen, setIsDeleteOpen] = React.useState(false);

  const {
    data: customer,
    isLoading,
    isError,
    error,
  } = useQuery({
    queryKey: ['customer_registration_details', id],
    queryFn: async () => {
      if (!id) return;
      return await fetchCustomerRegistrationDetailsById(id);
    },
    enabled: !!id,
  });

  if (!id) {
    return (
      <div className="p-6 text-sm text-slate-600">No customer id provided.</div>
    );
  }

  if (isLoading) {
    return <div className="p-6 text-sm text-slate-600">Loading customer…</div>;
  }

  if (isError) {
    return (
      <div className="p-6">
        <Alert variant="mono" icon="destructive">
          <AlertIcon>
            <RiErrorWarningFill />
          </AlertIcon>
          <AlertTitle>
            Failed to load customer:{' '}
            {(error as Error)?.message ?? 'Unknown error'}
          </AlertTitle>
        </Alert>
      </div>
    );
  }

  if (!customer) {
    return (
      <div className="p-6 text-sm text-slate-600">Customer not found.</div>
    );
  }

  return (
    <div className="w-full max-w-4xl mx-auto p-6 space-y-6">
      <div className="mb-4 flex items-start justify-between gap-3">
        <div>
          <h2 className="text-xl font-semibold">{customer.full_name}</h2>
          <p className="text-slate-500 text-sm">{customer.email}</p>
        </div>
        <div className="flex gap-2">
          <Button variant="destructive" onClick={() => setIsDeleteOpen(true)}>
            Delete
          </Button>

          <Button variant="outline" onClick={() => router.push('/customers')}>
            Back to list
          </Button>
        </div>
      </div>

      <div className="rounded-2xl border border-slate-200 bg-white shadow-sm">
        <div className="p-4 sm:p-6">
          <Row label="Full Name">{customer.full_name}</Row>
          <Row label="Company Name">{customer.company_name}</Row>
          <Row label="Email">{customer.email}</Row>
          <Row label="Mobile">{customer.mobile}</Row>
          <Row label="Country">{customer.country_name}</Row>
          <Row label="Company Website">
            <a
              href={customer.company_website}
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary underline break-all"
            >
              {customer.company_website}
            </a>
          </Row>
        </div>

        <div className="px-4 sm:px-6 pb-6 space-y-2 border-t">
          <Row label="Company Type">{customer.company_type_name}</Row>
          <Row label="Collaboration Goal">
            {customer.collaboration_goal_name}
          </Row>
          <Row label="Collaboration Manager">
            {customer.collaboration_manager_name}
          </Row>
          <Row label="Start Preference">{customer.start_preference_name}</Row>
          <Row label="Annual Revenue">
            {customer.annual_revenue_system_name}
          </Row>
        </div>
      </div>
      <CustomerDeleteDialog
        open={isDeleteOpen}
        closeDialog={() => setIsDeleteOpen(false)}
        customer={customer}
      />
    </div>
  );
}
