'use client';

import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { MessageCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinners';
import {
  getSiteContact,
  updateSiteContact,
  type SiteContact,
} from '@/network/apis/dashboard/marketplace/marketplace.apis';

/**
 * The WhatsApp number the public site offers visitors.
 *
 * It is edited here rather than set in an environment file because it is a
 * business detail, not a deployment one: the sales line changes, and that must
 * not wait for a release. Clearing the field removes the WhatsApp option from
 * the site — better than leaving a link that reaches nobody.
 */
export function ContactNumberCard() {
  const qc = useQueryClient();
  const [value, setValue] = useState('');
  const [touched, setTouched] = useState(false);

  const { data, isLoading } = useQuery<SiteContact>({
    queryKey: ['site-contact'],
    queryFn: getSiteContact,
  });

  // Show what is stored until the admin starts editing; after that their
  // typing wins, so a background refetch cannot overwrite it mid-edit.
  useEffect(() => {
    if (!touched && data) setValue(data.whatsapp_number ?? '');
  }, [data, touched]);

  const { mutate, isPending } = useMutation({
    mutationFn: () => updateSiteContact(value.trim()),
    onSuccess: (result) => {
      qc.setQueryData(['site-contact'], result);
      setTouched(false);
      setValue(result.whatsapp_number ?? '');
      toast.success(
        result.whatsapp_number
          ? `WhatsApp number set to +${result.whatsapp_number}`
          : 'WhatsApp number cleared — the site will hide the option',
      );
    },
    onError: (error: unknown) => {
      const response = (
        error as {
          response?: {
            data?: { message?: string; errors?: Record<string, string[]> };
          };
        }
      )?.response?.data;
      const firstFieldError = response?.errors
        ? Object.values(response.errors).flat()[0]
        : null;
      toast.error(
        firstFieldError ?? response?.message ?? 'Failed to save the number',
      );
    },
  });

  const digits = value.replace(/\D/g, '');
  // Empty is allowed on purpose: it is how the option is switched off.
  const valid = digits.length === 0 || (digits.length >= 8 && digits.length <= 15);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-base">
          <MessageCircle className="size-4 shrink-0" />
          Public WhatsApp number
        </CardTitle>
        <CardDescription>
          Shown on the marketing site as &ldquo;message us directly&rdquo;. Leave
          it empty to hide that option.
        </CardDescription>
      </CardHeader>

      <CardContent className="space-y-4">
        <div>
          <Label>Number with country code</Label>
          <Input
            dir="ltr"
            inputMode="tel"
            placeholder="966501234567"
            value={value}
            disabled={isLoading}
            onChange={(e) => {
              setTouched(true);
              setValue(e.target.value);
            }}
            className="max-w-xs"
          />
          <p className="text-xs text-muted-foreground mt-1">
            Spaces, dashes and a leading + are fine. A Saudi number typed as
            05XXXXXXXX is saved as 9665XXXXXXXX.
          </p>
          {!valid ? (
            <p className="text-xs text-red-600 mt-1">
              A number needs between 8 and 15 digits.
            </p>
          ) : null}
        </div>

        {data?.whatsapp_link ? (
          <p className="text-xs text-muted-foreground">
            Visitors currently reach{' '}
            <a
              href={data.whatsapp_link}
              target="_blank"
              rel="noreferrer"
              className="underline"
              dir="ltr"
            >
              {data.whatsapp_link}
            </a>
          </p>
        ) : (
          <p className="text-xs text-muted-foreground">
            No number set — the site is not showing a WhatsApp option.
          </p>
        )}

        <div className="pt-2 border-t flex justify-end">
          <Button onClick={() => mutate()} disabled={!valid || isPending || isLoading}>
            {isPending ? <Spinner className="size-4 animate-spin mr-2" /> : null}
            Save
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
