import { apiConfig } from '@/config/api.config';
import { useManageProviderContext } from '../hooks/useManageProviderContext';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
import React, { useCallback, useEffect, useState } from 'react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { CustomerProps } from './AddDialog';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';

const API_URL_CUSTOMER = apiConfig.service_customer;
const API_URL_MASTERDATA = apiConfig.service_master_data;

const EditDialog = () => {
  const { showEditDialog, handleEditDialog, selectedProvider, provider } =
    useManageProviderContext();
  const { reload } = useDataGrid();
  const { PutData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const created_time = new Date();
  const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
  const [open, setOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const validateForm = () => {
    const requiredFields = [
      { key: 'name', label: 'Name' },
      { key: 'description', label: 'Description' },
      { key: 'type', label: 'Type' },
      { key: 'status', label: 'Status' }
    ];
    const newErrors: Record<string, string> = {};
    let isValid = true;
    requiredFields.forEach(({ key, label }) => {
      if (
        formField[key as keyof typeof formField] === '' ||
        formField[key as keyof typeof formField] === null ||
        formField[key as keyof typeof formField] === undefined
      ) {
        newErrors[key] = `${label} is required`;
        toast.error(`${label} is required`);
        isValid = false;
      }
    });
    setErrors(newErrors);
    return isValid;
  };
  const initialState: {
    name: string;
    description: string;
    type: string;
    status: string;
    agent: string | null;
    updated_by: string;
    updated_at: string;
  } = {
    name: '',
    description: '',
    type: '',
    status: '',
    agent: null,
    updated_by: '',
    updated_at: ''
  };

  const [formField, setFormField] = useState(initialState);
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const resetForm = () => {
    setFormField(initialState);
    setErrors({});
  };

  const doUpdateProvider = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      setIsSubmitting(true);

      try {
        const response = await PutData(
          `${API_URL_MASTERDATA}/provider/update/${selectedProvider}`,
          formField
        );

        if (response?.status) {
          resetForm();
          handleEditDialog(false, null);
          toast.success('Provider updated successfully.');
          const createActivity = {
            module: 'Manage Provider',
            description: `Update Provider => ${selectedProvider}`,
            action: 'U'
          };

          doSaveLogActivity(createActivity);
          reload();
        } else {
          toast.error('Failed to update provider.');
          setAlert({ show: true, message: response?.message });
        }
      } catch (error) {
        toast.error('Something went wrong, please try again.');
      } finally {
        setIsSubmitting(false);
      }
    },
    [selectedProvider, formField]
  );

  const getCustomerList = async (sorting: any) => {
    try {
      sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });

      // console.log('CUSTOMER: ', response?.data);
      setCustomers(response?.data.list);
    } catch (error) {
      console.error('Error fetching customer', error);
    }
  };

  const doFetchData = useCallback(async (id: string) => {
    setIsLoading(true);
    const minDelay = new Promise((resolve) => setTimeout(resolve, 300));
    const fetchData = GetData(`${API_URL_MASTERDATA}/provider/getdata/${id}`, { id });
    const [response] = await Promise.all([fetchData, minDelay]);
    // console.log(response);
    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        name: response?.data.name,
        description: response?.data.description,
        type: response?.data.type,
        status: response?.data.status,
        transaction_type: response?.data.transaction_type?.id || '',
        agent: response?.data.agent?.id || null
      }));
    }
    setIsLoading(false);
  }, []);

  const handleUpdate = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsSubmitting(true);
    if (!validateForm()) {
      setIsSubmitting(false);
      return;
    }
    doUpdateProvider(e);
    // console.log(formField);
    // setAlert({ show: false, message: '' });
  };

  useEffect(() => {
    if (showEditDialog === false) {
      resetForm();
    }
  }, [showEditDialog]);

  useEffect(() => {
    if (selectedProvider) {
      doFetchData(selectedProvider);
    }
  }, [selectedProvider]);

  useEffect(() => {
    if (showEditDialog) {
      setFormField({
        ...formField,
        updated_by: parsedUser.username,
        updated_at: formattedTime
      });
    }
  }, [formattedTime]);

  useEffect(() => {
    if (showEditDialog) {
      getCustomerList([{ id: 'id', desc: false }]);
    }
  }, [showEditDialog]);

  return (
    <Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Provider - Update</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody>
          <div className="flex flex-col">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}

            {isLoading ? (
              <div className="flex flex-col items-center justify-center p-8">
                <div className="flex w-full space-x-4 animate-pulse">
                  <div className="flex-1 py-1 space-y-4">
                    <div className="w-3/4 h-4 bg-gray-200 rounded"></div>
                    <div className="space-y-2">
                      <div className="h-4 bg-gray-200 rounded"></div>
                      <div className="w-5/6 h-4 bg-gray-200 rounded"></div>
                    </div>
                  </div>
                </div>
                <p className="mt-4 text-gray-500">Loading Provider Details...</p>
              </div>
            ) : (
              <form onSubmit={handleUpdate}>
                <div className="grid gap-5 card-body">
                  <div className="w-full">
                    <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                      <label className="flex items-center gap-1 form-label max-w-56">
                        Name<span className="text-red-500">*</span>
                      </label>
                      <div className="flex flex-col grow">
                        <Input
                          className={`input ${errors.name ? 'border-red-500' : ''}`}
                          type="text"
                          value={formField.name}
                          onChange={({ target }) => {
                            setFormField((prev) => ({ ...prev, name: target.value }));
                            if (target.value) setErrors((prev) => ({ ...prev, name: '' }));
                          }}
                        />
                        {errors.name && (
                          <span className="mt-1 text-xs text-red-500">{errors.name}</span>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Description */}
                  <div className="w-full">
                    <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                      <label className="flex items-center gap-1 form-label max-w-56">
                        Description<span className="text-red-500">*</span>
                      </label>
                      <div className="flex flex-col grow">
                        <Input
                          className={`input ${errors.description ? 'border-red-500' : ''}`}
                          type="text"
                          value={formField.description}
                          onChange={(e) => {
                            setFormField({ ...formField, description: e.target.value });
                            if (e.target.value) setErrors((prev) => ({ ...prev, description: '' }));
                          }}
                        />
                        {errors.description && (
                          <span className="mt-1 text-xs text-red-500">{errors.description}</span>
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="w-full">
                    <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                      <label className="flex items-center gap-1 form-label max-w-56">
                        Type<span className="text-red-500">*</span>
                      </label>
                      <div className="flex flex-col grow">
                        <Select
                          value={formField.type}
                          onValueChange={(value) => {
                            setFormField({ ...formField, type: value });
                            setErrors((prev) => ({ ...prev, type: '' }));
                          }}
                        >
                          <SelectTrigger className={`input ${errors.type ? 'border-red-500' : ''}`}>
                            <SelectValue placeholder="Select Type" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="h2h">Host to Host</SelectItem>
                            <SelectItem value="agent">Agent</SelectItem>
                          </SelectContent>
                        </Select>
                        {errors.type && (
                          <span className="mt-1 text-xs text-red-500">{errors.type}</span>
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="w-full">
                    <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                      <label className="flex items-center gap-1 form-label max-w-56">
                        Status<span className="text-red-500">*</span>
                      </label>
                      <div className="flex flex-col grow">
                        <Select
                          value={formField.status}
                          onValueChange={(value) => {
                            setFormField({ ...formField, status: value });
                            setErrors((prev) => ({ ...prev, status: '' }));
                          }}
                        >
                          <SelectTrigger
                            className={`input ${errors.status ? 'border-red-500' : ''}`}
                          >
                            <SelectValue placeholder="Select Status" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="Y">Active</SelectItem>
                            <SelectItem value="N">Inactive</SelectItem>
                          </SelectContent>
                        </Select>
                        {errors.status && (
                          <span className="mt-1 text-xs text-red-500">{errors.status}</span>
                        )}
                      </div>
                    </div>
                  </div>

                  {formField.type === 'agent' ? (
                    <div className="w-full">
                      <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                        <label className="flex items-center gap-1 form-label max-w-56">
                          Agent Name<span className="text-red-500">*</span>
                        </label>
                        <Popover open={open} onOpenChange={setOpen}>
                          <PopoverTrigger asChild>
                            <button
                              type="button"
                              className="col-span-5 text-left input"
                              style={{ color: 'inherit' }}
                            >
                              {customers.find((customer) => customer.id === formField.agent)
                                ?.username || 'Select Agent'}
                            </button>
                          </PopoverTrigger>
                          <PopoverContent className="w-[400px] p-0">
                            <Command>
                              <CommandInput placeholder="Search Agent..." />
                              <CommandList
                                className="max-h-[300px] overflow-y-auto"
                                style={{ touchAction: 'pan-y' }}
                                onWheel={(e) => {
                                  e.currentTarget.scrollTop += e.deltaY;
                                }}
                              >
                                <CommandEmpty>No Agent found.</CommandEmpty>
                                <CommandGroup>
                                  {customers.map((customer) => (
                                    <CommandItem
                                      key={customer.id}
                                      value={customer.username}
                                      onSelect={() => {
                                        setFormField({
                                          ...formField,
                                          agent: customer.id
                                        });
                                        setOpen(false);
                                      }}
                                    >
                                      {customer.username}
                                    </CommandItem>
                                  ))}
                                </CommandGroup>
                              </CommandList>
                            </Command>
                          </PopoverContent>
                        </Popover>
                      </div>
                    </div>
                  ) : (
                    <div className="w-full">
                      <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                        <label className="flex items-center gap-1 form-label max-w-56">
                          Agent Name
                        </label>
                        <Input
                          type="text"
                          placeholder="Type Agent Only"
                          readOnly
                          className="cursor-not-allowed"
                        />
                      </div>
                    </div>
                  )}

                  <div className="flex justify-end">
                    <Button variant="default" type="submit" disabled={isSubmitting}>
                      {isSubmitting ? (
                        <RefreshCw className="w-8 h-8 mx-3 text-white animate-spin" />
                      ) : (
                        'Save Changes'
                      )}
                    </Button>
                  </div>
                </div>
              </form>
            )}
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
