import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card } from 'primereact/card';
import { Dialog } from 'primereact/dialog';
import { InputText } from 'primereact/inputtext';
import { InputTextarea } from 'primereact/inputtextarea';
import { FileUpload } from 'primereact/fileupload';
import Button from '../shared/components/_V2/Button';
import Dropdown from '../shared/components/_V2/Dropdown';
import Divider from '../shared/components/_V1/Divider';

import fusero_logo from '../assets/fusero_logo.svg';
import roc_logo from '../assets/roc_logo.png';
import { useSystemStore } from '../state/stores/useSystemStore';

export type SystemDropdownOption = {
  id: number;
  label: string;
  name: string;
  businessLabel: string;
  urlSlug: string;
  logo: string;
  category: string;
  method?: string;
  path?: string;
  description?: string;
  publicPath?: string;
  enterprises?: Enterprise[];
};

export type Enterprise = {
  id: number;
  name: string;
};

export interface SystemSelectionModalProps {
  systemDetails: SystemDropdownOption | null;
  onSystemSelected: (systemData: any) => void;
  onLogoChange: (newLogoPath: string) => void;
}

// Add system default routes configuration
const systemDefaultRoutes = {
  council: 'chat',
  fusemind: 'home',
};

const HARDCODED_SYSTEMS = [
  {
    id: 1,
    label: 'Canvas API',
    name: 'Canvas API',
    businessLabel: 'Canvas',
    urlSlug: 'canvas',
    logo: roc_logo,
    category: 'Apps',
    method: 'GET',
    path: '/api/v1/canvas-endpoints',
    description: 'Integration with Canvas LMS',
    publicPath: '/canvas-endpoints',
    enterprises: [],
  },
  {
    id: 2,
    label: 'FuseMind',
    name: 'FuseMind',
    businessLabel: 'FuseMind',
    urlSlug: 'fusemind',
    logo: fusero_logo,
    category: 'Apps',
    method: 'GET',
    path: '/api/v1/fusemind',
    description: 'FuseMind AI Platform',
    publicPath: '/fusemind',
    enterprises: [],
  },
];

const SystemSelectionModal = ({ systemDetails }: SystemSelectionModalProps) => {
  const navigate = useNavigate();
  const [selectedSystem, setSelectedSystem] = useState<SystemDropdownOption | null>(null);
  const [selectedEnterprise, setSelectedEnterprise] = useState<number | null>(null);
  const [showAddSystemDialog, setShowAddSystemDialog] = useState(false);
  const [showEditLogoDialog, setShowEditLogoDialog] = useState(false);
  const [systems, setSystems] = useState<SystemDropdownOption[]>(HARDCODED_SYSTEMS);
  const [isLoading, setIsLoading] = useState(false);
  const [uploadedLogo, setUploadedLogo] = useState<string | null>(null);
  const [newSystem, setNewSystem] = useState({
    name: '',
    businessLabel: '',
    urlSlug: '',
    method: '',
    path: '',
    description: '',
    publicPath: '',
  });
  const { setSystem } = useSystemStore();

  useEffect(() => {
    [fusero_logo].forEach((image) => {
      const img = new Image();
      img.src = image;
    });
    if (systemDetails) {
      setSelectedSystem(systemDetails);
      setSystem(systemDetails);
    }
  }, [systemDetails, setSystem]);

  const handleSystemChange = useCallback(
    (e: { value: SystemDropdownOption }) => {
      setSelectedSystem(e.value);
      setSystem(e.value);
    },
    [setSystem]
  );

  const handleSelectSystem = () => {
    if (selectedSystem) {
      navigate(`/dashboard/${selectedSystem.urlSlug}`);
    }
  };

  const handleEnterpriseChange = useCallback((e: { value: number }) => {
    setSelectedEnterprise(e.value);
  }, []);

  const handleLogoUpload = async (event: any) => {
    const file = event.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const base64 = e.target?.result as string;
        setUploadedLogo(base64);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleUpdateLogo = async () => {
    if (!selectedSystem || !uploadedLogo) return;

    try {
      // Upload the new logo
      const logoResponse = await fetch('/api/v1/assets', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: `${selectedSystem.name}-logo`,
          type: 'image',
          data: uploadedLogo,
          mimeType: 'image/png',
          assetType: 'system_logo',
        }),
      });

      if (!logoResponse.ok) {
        throw new Error('Failed to upload logo');
      }

      const logoData = await logoResponse.json();

      // Update the system with the new logo ID
      const response = await fetch(`/api/v1/apps/${selectedSystem.id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          logoId: logoData.id,
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to update system logo');
      }

      const updatedSystem = await response.json();

      // Update the local state
      setSystems(prev => prev.map(system =>
        system.id === selectedSystem.id
          ? { ...system, logo: updatedSystem.logo || fusero_logo }
          : system
      ));

      setSelectedSystem(prev => prev ? { ...prev, logo: updatedSystem.logo || fusero_logo } : null);
      setShowEditLogoDialog(false);
      setUploadedLogo(null);
    } catch (error) {
      console.error('Error updating logo:', error);
    }
  };

  const handleAddSystem = async () => {
    try {
      // First upload the logo if exists
      let logoId = null;
      if (uploadedLogo) {
        const logoResponse = await fetch('/api/v1/assets', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: `${newSystem.name}-logo`,
            type: 'image',
            data: uploadedLogo,
            mimeType: 'image/png',
            assetType: 'system_logo',
          }),
        });

        if (!logoResponse.ok) {
          throw new Error('Failed to upload logo');
        }

        const logoData = await logoResponse.json();
        logoId = logoData.id;
      }

      // Then create the system
      const response = await fetch('/api/v1/apps', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...newSystem,
          logoId,
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to create system');
      }

      const createdSystem = await response.json();
      const systemOption: SystemDropdownOption = {
        ...createdSystem,
        label: createdSystem.name,
        businessLabel: createdSystem.businessLabel || createdSystem.name,
        logo: createdSystem.logo || fusero_logo,
        category: 'Apps',
      };

      setSystems(prev => [...prev, systemOption]);
      setShowAddSystemDialog(false);
      setNewSystem({
        name: '',
        businessLabel: '',
        urlSlug: '',
        method: '',
        path: '',
        description: '',
        publicPath: '',
      });
      setUploadedLogo(null);
    } catch (error) {
      console.error('Error creating system:', error);
    }
  };

  return (
    <>
      <Card
        style={{ border: 'none', boxShadow: 'none', overflow: 'hidden' }}
        className='px-8 bg-white'
      >
        <h2 className='my-2 text-xl font-semibold text-gray-700'>Apps & Flows</h2>
        <div className='flex items-center gap-4'>
          <Dropdown
            id='system'
            value={selectedSystem}
            options={systems}
            onChange={handleSystemChange}
            optionLabel='businessLabel'
            placeholder='Select an integration'
            className='flex-1'
            loading={isLoading}
          />
          {/* <Button
            label='Add System'
            onClick={() => setShowAddSystemDialog(true)}
            className='px-4 py-2 text-white transition-colors bg-blue-500 border-2 border-blue-500 rounded-md hover:bg-white hover:text-blue-500'
          /> */}
        </div>
        {selectedSystem && selectedSystem.enterprises && (
          <Dropdown
            id='enterprise'
            value={selectedEnterprise}
            options={selectedSystem.enterprises.map((enterprise) => ({
              label: enterprise.name,
              value: enterprise.id,
            }))}
            onChange={handleEnterpriseChange}
            placeholder='Select an enterprise'
          />
        )}
        <Button
          label='Select System'
          onClick={handleSelectSystem}
          className='w-full mt-4 text-white transition-colors bg-teal-500 border-2 border-teal-500 rounded-md hover:bg-white hover:text-teal-500'
        />
        <Divider />
      </Card>
      {selectedSystem && (
        <div className="relative">
          <img
            src={selectedSystem.logo}
            alt={`${selectedSystem.label} Logo`}
            className='w-48'
          />
          <Button
            label="Edit Logo"
            onClick={() => setShowEditLogoDialog(true)}
            className="absolute bottom-0 right-0 px-2 py-1 text-sm text-white bg-blue-500 rounded hover:bg-blue-600"
          />
        </div>
      )}

      <Dialog
        header="Add New System"
        visible={showAddSystemDialog}
        style={{ width: '50vw' }}
        onHide={() => setShowAddSystemDialog(false)}
        footer={
          <div>
            <Button
              label="Cancel"
              onClick={() => setShowAddSystemDialog(false)}
              className="mr-2"
            />
            <Button
              label="Create"
              onClick={handleAddSystem}
              className="bg-blue-500 text-white"
            />
          </div>
        }
      >
        <div className="flex flex-col gap-4">
          <div>
            <label className="block mb-2">Name</label>
            <InputText
              value={newSystem.name}
              onChange={(e) => setNewSystem({ ...newSystem, name: e.target.value })}
              className="w-full"
            />
          </div>
          <div>
            <label className="block mb-2">Business Label</label>
            <InputText
              value={newSystem.businessLabel}
              onChange={(e) => setNewSystem({ ...newSystem, businessLabel: e.target.value })}
              className="w-full"
            />
          </div>
          <div>
            <label className="block mb-2">URL Slug</label>
            <InputText
              value={newSystem.urlSlug}
              onChange={(e) => setNewSystem({ ...newSystem, urlSlug: e.target.value })}
              className="w-full"
            />
          </div>
          <div>
            <label className="block mb-2">Method</label>
            <InputText
              value={newSystem.method}
              onChange={(e) => setNewSystem({ ...newSystem, method: e.target.value })}
              className="w-full"
            />
          </div>
          <div>
            <label className="block mb-2">Path</label>
            <InputText
              value={newSystem.path}
              onChange={(e) => setNewSystem({ ...newSystem, path: e.target.value })}
              className="w-full"
            />
          </div>
          <div>
            <label className="block mb-2">Description</label>
            <InputTextarea
              value={newSystem.description}
              onChange={(e) => setNewSystem({ ...newSystem, description: e.target.value })}
              className="w-full"
            />
          </div>
          <div>
            <label className="block mb-2">Public Path</label>
            <InputText
              value={newSystem.publicPath}
              onChange={(e) => setNewSystem({ ...newSystem, publicPath: e.target.value })}
              className="w-full"
            />
          </div>
          <div>
            <label className="block mb-2">Logo</label>
            <FileUpload
              mode="basic"
              name="logo"
              accept="image/*"
              maxFileSize={1000000}
              chooseLabel="Upload Logo"
              onUpload={handleLogoUpload}
              auto
              customUpload
            />
            {uploadedLogo && (
              <div className="mt-2">
                <img src={uploadedLogo} alt="Uploaded logo" className="w-32 h-32 object-contain" />
              </div>
            )}
          </div>
        </div>
      </Dialog>

      <Dialog
        header="Update System Logo"
        visible={showEditLogoDialog}
        style={{ width: '30vw' }}
        onHide={() => setShowEditLogoDialog(false)}
        footer={
          <div>
            <Button
              label="Cancel"
              onClick={() => setShowEditLogoDialog(false)}
              className="mr-2"
            />
            <Button
              label="Update"
              onClick={handleUpdateLogo}
              className="bg-blue-500 text-white"
              disabled={!uploadedLogo}
            />
          </div>
        }
      >
        <div className="flex flex-col gap-4">
          <div>
            <label className="block mb-2">Current Logo</label>
            {selectedSystem && (
              <img
                src={selectedSystem.logo}
                alt="Current logo"
                className="w-32 h-32 object-contain mb-4"
              />
            )}
          </div>
          <div>
            <label className="block mb-2">New Logo</label>
            <FileUpload
              mode="basic"
              name="logo"
              accept="image/*"
              maxFileSize={1000000}
              chooseLabel="Upload New Logo"
              onUpload={handleLogoUpload}
              auto
              customUpload
            />
            {uploadedLogo && (
              <div className="mt-2">
                <img src={uploadedLogo} alt="New logo preview" className="w-32 h-32 object-contain" />
              </div>
            )}
          </div>
        </div>
      </Dialog>
    </>
  );
};

export default SystemSelectionModal;
