import React, { HTMLProps, useEffect, useMemo, useState } from "react";
import { BranchOffice, Company, emptyAddress, emptyBranchOffice, emptyCompany, formatAddress } from "@/data";
import { sampleCompanies } from "@/provider/dummy";
import { Autocomplete } from "@material-ui/lab";
import { Grid, TextField, Typography } from "@material-ui/core";
import { formFieldProps } from "./helpers";

export type CompanyFormProps = {}

export type BranchOfficeProps = {
    company: Company,
    disabled?: boolean
}

export const CompanyItem = ({ company, ...props }: { company: Company } & HTMLProps<any>) => (
    <div className="company-item" { ...props }>
        <div>{ company.name }</div>
        <Typography variant="caption">NIP: <strong>{ company.nip }</strong></Typography>
    </div>
)

export const OfficeItem = ({ office, ...props }: { office: BranchOffice } & HTMLProps<any>) => (
    <div className="office-item" { ...props }>
        <div>{ office.address.city }</div>
        <Typography variant="caption">{ formatAddress(office.address) }</Typography>
    </div>
)

export const BranchForm: React.FC<BranchOfficeProps> = ({ company, disabled = false }) => {
    const [office, setOffice] = useState<BranchOffice>(emptyBranchOffice)

    const canEdit = useMemo(() => !office.id && !disabled, [office.id, disabled]);

    const fieldProps = formFieldProps(office.address, address => setOffice({ ...office, address }))

    const handleCityChange = (event: any, value: BranchOffice | string | null) => {
        if (typeof value === "string") {
            setOffice({
                ...emptyBranchOffice,
                address: {
                    ...emptyAddress,
                    city: value,
                }
            });
        } else if (typeof value === "object" && value !== null) {
            setOffice(value);
        } else {
            setOffice(emptyBranchOffice);
        }
    }

    const handleCityInput = (event: any, value: string) => {
        const base = office.id ? emptyBranchOffice : office;
        setOffice({
            ...base,
            address: {
                ...base.address,
                city: value,
            }
        })
    }

    useEffect(() => void (office.id && setOffice(emptyBranchOffice)), [company])

    return (
        <div>
            <Grid container>
                <Grid item md={ 7 }>
                    <Autocomplete options={ company?.offices || [] }
                                  disabled={ disabled }
                                  getOptionLabel={ office => typeof office == "string" ? office : office.address.city }
                                  renderOption={ office => <OfficeItem office={ office }/> }
                                  renderInput={ props => <TextField { ...props } label={ "Miasto" } fullWidth/> }
                                  onChange={ handleCityChange }
                                  onInputChange={ handleCityInput }
                                  inputValue={ office.address.city }
                                  value={ office.id ? office : null }
                                  freeSolo
                    />
                </Grid>
                <Grid item md={ 2 }>
                    <TextField label={ "Kod pocztowy" } fullWidth disabled={ !canEdit } { ...fieldProps("postalCode") }/>
                </Grid>
                <Grid item md={ 3 }>
                    <TextField label={ "Kraj" } fullWidth disabled={ !canEdit } { ...fieldProps("country") }/>
                </Grid>
                <Grid item md={ 10 }>
                    <TextField label={ "Ulica" } fullWidth disabled={ !canEdit } { ...fieldProps("street") }/>
                </Grid>
                <Grid item md={ 2 }>
                    <TextField label={ "Nr Budynku" } fullWidth disabled={ !canEdit } { ...fieldProps("building") }/>
                </Grid>
            </Grid>
        </div>
    )
}

export const CompanyForm: React.FunctionComponent<CompanyFormProps> = props => {
    const [company, setCompany] = useState<Company>(emptyCompany);
    const canEdit = useMemo(() => !company.id, [company.id]);

    const fieldProps = formFieldProps(company, setCompany)

    const handleCompanyChange = (event: any, value: Company | string | null) => {
        if (typeof value === "string") {
            setCompany({
                ...emptyCompany,
                name: value,
            });
        } else if (typeof value === "object" && value !== null) {
            setCompany(value);
        } else {
            setCompany(emptyCompany);
        }
    }

    return (
        <>
            <Grid container>
                <Grid item>
                    <Autocomplete options={ sampleCompanies }
                                  getOptionLabel={ option => option.name }
                                  renderOption={ company => <CompanyItem company={ company }/> }
                                  renderInput={ props => <TextField { ...props } label={ "Nazwa firmy" } fullWidth/> }
                                  onChange={ handleCompanyChange }
                                  freeSolo
                    />
                </Grid>
                <Grid item md={ 4 }>
                    <TextField label={ "NIP" } fullWidth { ...fieldProps("nip") } disabled={ !canEdit }/>
                </Grid>
                <Grid item md={ 8 }>
                    <TextField label={ "Url" } fullWidth { ...fieldProps("url") } disabled={ !canEdit }/>
                </Grid>
            </Grid>
            <Typography variant="subtitle1">Oddział</Typography>
            <BranchForm company={ company }/>
        </>
    )
}

