import React, { useEffect, useMemo, useState } from 'react';
import { Head, Link, router, usePage } from '@inertiajs/react';
import MainLayout from '@/layouts/MainLayout';
import { Button, Card, Col, Form, Row } from 'react-bootstrap';



type FieldOption = {
    value: string;
    label: string;
};

type TemplateField = {
    key: string;
    label: string;
    type: string;
    default?: any;
    visible?: boolean;
    required?: boolean;
    options?: FieldOption[];
    years_back?: number;
};

type TemplateSection = {
    key: string;
    label: string;
    type: string;
    fields?: TemplateField[];
    groups?: Array<{
        key: string;
        label: string;
        fields: TemplateField[];
    }>;
    rows?: Array<{
        key: string;
        label: string;
        affects_compliance?: boolean;
    }>;
    extra_fields?: TemplateField[];
    min_items?: number;
    max_items?: number;
    item_label?: string;
    has_comments?: boolean;
    requires_comment_on_fail?: boolean;
    add_button_label?: string;
};

type PageProps = {
    mode: 'edit';
    template: {
        key: string;
        name: string;
        pdf_view: string;
        header: {
            fields: TemplateField[];
        };
        body: {
            sections: TemplateSection[];
        };
        footer: {
            fields: TemplateField[];
        };
        compliance: Record<string, any>;
    };
    default_data: {
        header: Record<string, any>;
        body: Record<string, any>;
        footer: Record<string, any>;
        meta: Record<string, any>;
    };
    report: {
        id: number;
        account_id: number | null;
        service_date: string | null;
        next_service_date: string | null;
        report_number: string | null;
        type: string | null;
        type_label?: string | null;
        template_key: string | null;
        status: string;
        compliant: boolean;
        data: {
            header?: Record<string, any>;
            body?: Record<string, any>;
            footer?: Record<string, any>;
            meta?: Record<string, any>;
        };
        account?: {
            id: number;
            company_name: string;
            suffix?: string | null;
        } | null;
    };
    auth?: {
        user?: {
            id?: number;
            name?: string;
            email?: string;
        };
    };
};

type StatusAnswer = '' | 'pass' | 'fail' | 'na';

type ContactOption = {
    id: number;
    label: string;
};

    const buildDefaultChecklistRows = (rows: Array<{ key: string; label: string }>) => {
        return rows.map((row) => ({
            key: row.key,
            label: row.label,
            answer: '',
            repaired: false,
        }));
    };

    const toDateInput = (val?: string | null) => {
        if (!val) return '';
    
        const s = String(val).trim();
    
        if (/^\d{4}-\d{2}-\d{2}/.test(s)) {
            return s.substring(0, 10);
        }
    
        const m = s.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
        if (m) {
            const [, mm, dd, yyyy] = m;
            return `${yyyy}-${mm}-${dd}`;
        }
    
        return '';
    };
    
    const toTimeInput = (val?: string | null) => {
        if (!val) return '';
        return String(val).substring(0, 5);
    };
    
    const calculateTotalHours = (start?: string | null, end?: string | null): string => {
        const s = toTimeInput(start);
        const e = toTimeInput(end);
    
        if (!s || !e) return '';
    
        const [startHour, startMinute] = s.split(':').map(Number);
        const [endHour, endMinute] = e.split(':').map(Number);
    
        if (
            Number.isNaN(startHour) ||
            Number.isNaN(startMinute) ||
            Number.isNaN(endHour) ||
            Number.isNaN(endMinute)
        ) {
            return '';
        }
    
        let startTotal = startHour * 60 + startMinute;
        let endTotal = endHour * 60 + endMinute;
    
        if (endTotal < startTotal) {
            endTotal += 24 * 60;
        }
    
        return ((endTotal - startTotal) / 60).toFixed(1);
    };

    const normalizeYesNo = (val: any): string => {
        if (val === true || String(val).toLowerCase() === 'true' || String(val).toLowerCase() === 'yes') {
            return 'Yes';
        }
        if (val === false || String(val).toLowerCase() === 'false' || String(val).toLowerCase() === 'no') {
            return 'No';
        }
        return val ?? '';
    };  
    
    const normalizeChecklistAnswer = (value: any): StatusAnswer => {
        const v = String(value ?? '').trim().toLowerCase();
    
        if (v === 'pass' || v === 'passed' || v === 'yes' || v === 'y') {
            return 'pass';
        }
    
        if (v === 'fail' || v === 'failed' || v === 'no' || v === 'n') {
            return 'fail';
        }
    
        if (v === 'na' || v === 'n/a' || v === 'not applicable') {
            return 'na';
        }
    
        return '';
    };    
        
    export default function ServiceReportsEdit() {
        const { props } = usePage<PageProps>();
        const { template, report, auth } = props;
    
        const initialData = useMemo(() => {
            const baseData = JSON.parse(
                JSON.stringify(
                    report?.data ?? {
                        header: {},
                        body: {},
                        footer: {},
                        meta: {},
                    }
                )
            );
        
            const sections = template?.body?.sections ?? [];
            const nextBody = { ...(baseData.body ?? {}) };
            const legacyBody = nextBody as Record<string, any>;
            const existingServiceDetails =
                nextBody.service_details && typeof nextBody.service_details === 'object'
                    ? nextBody.service_details
                    : {};
            
            nextBody.service_details = {
                manufacturer:
                    existingServiceDetails.manufacturer ??
                    legacyBody.manufacturer ??
                    legacyBody.gi_manufacturer ??
                    '',
                model:
                    existingServiceDetails.model ??
                    legacyBody.model ??
                    legacyBody.gi_model ??
                    '',
                tank_size:
                    existingServiceDetails.tank_size ??
                    legacyBody.tank_size ??
                    legacyBody.size ??
                    legacyBody.interceptor_size ??
                    '',
                location:
                    existingServiceDetails.location ??
                    legacyBody.location ??
                    legacyBody.interceptor_location ??
                    '',
                solids_percent:
                    existingServiceDetails.solids_percent ??
                    legacyBody.solids_percent ??
                    legacyBody.solids ??
                    legacyBody.gl_1_solids ??
                    '',
                grease_percent:
                    existingServiceDetails.grease_percent ??
                    legacyBody.grease_percent ??
                    legacyBody.grease ??
                    legacyBody.gl_1_grease ??
                    '',
                liquid_percent:
                    existingServiceDetails.liquid_percent ??
                    legacyBody.liquid_percent ??
                    legacyBody.liquid ??
                    legacyBody.gl_1_liquid ??
                    '',
                total_liquid_collected:
                    existingServiceDetails.total_liquid_collected ??
                    legacyBody.total_liquid_collected ??
                    legacyBody.total_liquid ??
                    legacyBody.liquid_collected ??
                    '',
            };
        
            sections.forEach((section: TemplateSection) => {
                if (section.type !== 'checklist' || !Array.isArray(section.rows)) {
                    return;
                }
            
                const existingRows = Array.isArray(nextBody[section.key]) ? nextBody[section.key] : [];
            
                if (existingRows.length > 0) {
                    nextBody[section.key] = existingRows.map((row: any, index: number) => ({
                        key: row?.key ?? section.rows?.[index]?.key ?? '',
                        label: row?.label ?? section.rows?.[index]?.label ?? '',
                        answer: normalizeChecklistAnswer(row?.answer),
                        repaired: typeof row?.repaired === 'boolean' ? row.repaired : false,
                    }));
                    return;
                }
            
                const checklistMap =
                    nextBody[section.key] &&
                    !Array.isArray(nextBody[section.key]) &&
                    typeof nextBody[section.key] === 'object'
                        ? (nextBody[section.key] as Record<string, any>)
                        : null;
            
                if (checklistMap) {
                    nextBody[section.key] = section.rows.map((row) => ({
                        key: row.key,
                        label: row.label,
                        answer: normalizeChecklistAnswer(checklistMap[row.key]),
                        repaired: false,
                    }));
                    return;
                }
            
                const legacyChecklist =
                    Array.isArray(legacyBody.checklist) ? legacyBody.checklist :
                    Array.isArray(legacyBody.inspections) ? legacyBody.inspections :
                    [];
            
                if (legacyChecklist.length > 0) {
                    nextBody[section.key] = legacyChecklist.map((row: any, index: number) => ({
                        key: row?.key ?? section.rows?.[index]?.key ?? '',
                        label: row?.label ?? section.rows?.[index]?.label ?? '',
                        answer: normalizeChecklistAnswer(row?.answer ?? row?.result),
                        repaired: typeof row?.repaired === 'boolean' ? row.repaired : false,
                    }));
                    return;
                }
            
                nextBody[section.key] = buildDefaultChecklistRows(section.rows);
            });
        
            baseData.body = nextBody;
        
            baseData.header = {
                ...(baseData.header ?? {}),
                service_date: toDateInput(baseData.header?.service_date || report.service_date),
                start_time: toTimeInput(baseData.header?.start_time),
                end_time: toTimeInput(baseData.header?.end_time),
                total_hours:
                    baseData.header?.total_hours ||
                    calculateTotalHours(baseData.header?.start_time, baseData.header?.end_time),
                inspection: normalizeYesNo(baseData.header?.inspection),
                cleaned: normalizeYesNo(baseData.header?.cleaned),
                return_visit_required: normalizeYesNo(baseData.header?.return_visit_required),
            };
        
            return {
                account_id: report.account_id ?? '',
                service_date: toDateInput(report.service_date),
                next_service_date: toDateInput(report.next_service_date),
                report_number: report.report_number ?? '',
                status: report.status ?? 'draft',
                compliant: !!report.compliant,
                template_key: report.template_key ?? template.key,
                type:
                    report.type ??
                    (template.key === 'fs'
                        ? 'Fire Suppression'
                        : template.key === 'ke'
                            ? 'Kitchen Exhaust Hood Cleaning'
                            : template.key === 'pe'
                                ? 'Portable Extinguishers & Emergency Lights'
                                : template.key),
                data: baseData,
            };
            
        }, [report, template]);

    const [form, setForm] = useState(initialData);
    
    const headerData = form.data?.header ?? {};
    const bodyData = form.data?.body ?? {};
    const footerData = form.data?.footer ?? {};
    
    const renderRepeatableGroupedSection = (section: TemplateSection) => {
            const minItems = section.min_items ?? 1;
            const maxItems = section.max_items ?? 20;
            const addButtonLabel = section.add_button_label ?? `Add ${section.item_label ?? 'Item'}`;
            const fields = section.fields ?? [];
        
            let items = Array.isArray(bodyData[section.key]) ? bodyData[section.key] : [];
        
            if (items.length === 0) {
                items = Array.from({ length: minItems }, () => {
                    const row: Record<string, any> = {};
                    fields.forEach((field) => {
                        row[field.key] = field.default ?? '';
                    });
                    return row;
                });
            }
        
            const setItems = (nextItems: any[]) => {
                setForm((prev) => ({
                    ...prev,
                    data: {
                        ...prev.data,
                        body: {
                            ...(prev.data?.body ?? {}),
                            [section.key]: nextItems,
                        },
                    },
                }));
            };
        
            const setItemField = (index: number, fieldKey: string, value: any) => {
                const next = [...items];
                next[index] = {
                    ...next[index],
                    [fieldKey]: value,
                };
                setItems(next);
            };
        
            const addItem = () => {
                if (items.length >= maxItems) return;
        
                const row: Record<string, any> = {};
                fields.forEach((field) => {
                    row[field.key] = field.default ?? '';
                });
        
                setItems([...items, row]);
            };
        
            const removeItem = (index: number) => {
                const next = [...items];
                next.splice(index, 1);
                setItems(next.length ? next : []);
            };
        
            return (
                <Card className="gd-form-card mb-4" key={section.key}>
                    <Card.Body>
                        <h5 className="mb-3">{section.label}</h5>
        
                        {items.map((item: any, index: number) => (
                            <div
                                key={`${section.key}-${index}`}
                                className="border rounded p-3 mb-3 position-relative"
                            >
                                {section.key === 'emergency_lights' ? (
                                    <button
                                        type="button"
                                        className="btn btn-sm btn-link text-danger position-absolute top-0 end-0"
                                        onClick={() => removeItem(index)}
                                        style={{ textDecoration: 'none' }}
                                    >
                                        ✕
                                    </button>
                                ) : (
                                    index > 0 && (
                                        <button
                                            type="button"
                                            className="btn btn-sm btn-link text-danger position-absolute top-0 end-0"
                                            onClick={() => removeItem(index)}
                                            style={{ textDecoration: 'none' }}
                                        >
                                            ✕
                                        </button>
                                    )
                                )}
        
                                <Row className="g-3">
                                    {fields.map((field) => {
                                        if (
                                            section.key === 'fire_extinguishers' &&
                                            field.key === 'size_type_other' &&
                                            (item?.size_type ?? '') !== 'other'
                                        ) {
                                            return null;
                                        }
                                    
                                        return (
                                            <Col
                                                md={field.type === 'textarea' ? 12 : 6}
                                                key={`${section.key}-${index}-${field.key}`}
                                            >
                                                <Form.Group>
                                                    <Form.Label>{field.label}</Form.Label>
                                                    {renderSimpleField(
                                                        field,
                                                        item?.[field.key] ?? '',
                                                        (value) => setItemField(index, field.key, value)
                                                    )}
                                                </Form.Group>
                                            </Col>
                                        );
                                    })}
                                </Row>
                            </div>
                        ))}
        
                        <div className="mt-3 d-flex">
                            <Button
                                type="button"
                                variant="primary"
                                size="sm"
                                onClick={addItem}
                            >
                                {addButtonLabel}
                            </Button>
                        </div>
                    </Card.Body>
                </Card>
            );
        };     

        const [saving, setSaving] = useState(false);
        
        const [contactResults, setContactResults] = useState<ContactOption[]>([]);
        const [selectedOwner, setSelectedOwner] = useState<ContactOption | null>(null);
        
        const [technicianResults, setTechnicianResults] = useState<ContactOption[]>([]);
        const [selectedTechnician, setSelectedTechnician] = useState<ContactOption | null>(null);

    useEffect(() => {
        setForm(initialData);
    }, [initialData]);

    useEffect(() => {
        fetch(route('contacts.by-account') + `?account_id=54463`, {
            headers: { Accept: 'application/json' },
        })
            .then((res) => res.json())
            .then((data) => {
                setTechnicianResults(Array.isArray(data) ? data : []);
            })
            .catch(() => {
                setTechnicianResults([]);
                setSelectedTechnician(null);
            });
    }, []);

    useEffect(() => {
        if (!technicianResults.length) return;
    
        const existingId = headerData.technician_contact_id;
        const existingName = headerData.technician_name || '';
    
        const found =
            technicianResults.find((t) => t.id === Number(existingId || 0)) ??
            technicianResults.find((t) => t.label === existingName) ??
            null;
    
        if (found) {
            setSelectedTechnician(found);
            if (!headerData.technician_contact_id) {
                setHeaderField('technician_contact_id', found.id);
            }
        }
    }, [technicianResults, headerData.technician_contact_id, headerData.technician_name]);

    useEffect(() => {
        const accountId = Number(form.account_id || 0);
    
        if (!accountId) {
            setContactResults([]);
            return;
        }
    
        fetch(route('contacts.by-account') + `?account_id=${accountId}`, {
            headers: { Accept: 'application/json' },
        })
            .then((res) => res.json())
            .then((data) => {
                const results = Array.isArray(data) ? data : [];
                setContactResults(results);
    
                const existingOwnerId = Number(
                    headerData.owner_contact_id || headerData.owner_authorized_agent_id || 0
                );
                const existingOwnerName = (
                    headerData.owner_name || headerData.owner_authorized_agent_name || ''
                ).trim();
    
                const foundOwner =
                    results.find((c) => c.id === existingOwnerId) ??
                    results.find((c) => c.label === existingOwnerName) ??
                    null;
    
                setSelectedOwner(foundOwner);
    
                if (foundOwner) {
                    if (!headerData.owner_contact_id) {
                        setHeaderField('owner_contact_id', foundOwner.id);
                    }
                    if (!headerData.owner_name) {
                        setHeaderField('owner_name', foundOwner.label);
                    }
                    if (!headerData.owner_authorized_agent_id) {
                        setHeaderField('owner_authorized_agent_id', foundOwner.id);
                    }
                    if (!headerData.owner_authorized_agent_name) {
                        setHeaderField('owner_authorized_agent_name', foundOwner.label);
                    }
                }
            })
            .catch(() => {
                setContactResults([]);
                setSelectedOwner(null);
            });
    }, [
        form.account_id,
        headerData.owner_contact_id,
        headerData.owner_name,
        headerData.owner_authorized_agent_id,
        headerData.owner_authorized_agent_name,
    ]);
    
    useEffect(() => {
        if (!contactResults.length) return;
    
        const existingOwnerId = Number(
            headerData.owner_contact_id || headerData.owner_authorized_agent_id || 0
        );
        const existingOwnerName = (
            headerData.owner_name || headerData.owner_authorized_agent_name || ''
        ).trim();
    
        const found =
            contactResults.find((c) => c.id === existingOwnerId) ??
            contactResults.find((c) => c.label.trim() === existingOwnerName) ??
            null;
    
        if (found) {
            setSelectedOwner(found);
        
            if (!headerData.owner_contact_id) {
                setHeaderField('owner_contact_id', found.id);
            }
            if (!headerData.owner_name) {
                setHeaderField('owner_name', found.label);
            }
            if (!headerData.owner_authorized_agent_id) {
                setHeaderField('owner_authorized_agent_id', found.id);
            }
            if (!headerData.owner_authorized_agent_name) {
                setHeaderField('owner_authorized_agent_name', found.label);
            }
        }
    }, [
        contactResults,
        headerData.owner_contact_id,
        headerData.owner_name,
        headerData.owner_authorized_agent_id,
        headerData.owner_authorized_agent_name,
    ]);    

    useEffect(() => {
        const total = calculateTotalHours(headerData.start_time, headerData.end_time);
        setHeaderField('total_hours', total);
    }, [headerData.start_time, headerData.end_time]);

    const setRootField = (key: string, value: any) => {
        setForm((prev) => ({
            ...prev,
            [key]: value,
        }));
    };

    const setHeaderField = (key: string, value: any) => {
        setForm((prev) => ({
            ...prev,
            data: {
                ...prev.data,
                header: {
                    ...(prev.data?.header ?? {}),
                    [key]: value,
                },
            },
        }));
    };

    const setBodyField = (section: string, key: string, value: any) => {
        setForm((prev) => ({
            ...prev,
            data: {
                ...prev.data,
                body: {
                    ...(prev.data?.body ?? {}),
                    [section]: {
                        ...((prev.data?.body ?? {})[section] ?? {}),
                        [key]: value,
                    },
                },
            },
        }));
    };

    const setGroupedField = (section: string, group: string, key: string, value: any) => {
        setForm((prev) => ({
            ...prev,
            data: {
                ...prev.data,
                body: {
                    ...(prev.data?.body ?? {}),
                    [section]: {
                        ...((prev.data?.body ?? {})[section] ?? {}),
                        [group]: {
                            ...(((prev.data?.body ?? {})[section] ?? {})[group] ?? {}),
                            [key]: value,
                        },
                    },
                },
            },
        }));
    };

    const setFooterField = (key: string, value: any) => {
        setForm((prev) => ({
            ...prev,
            data: {
                ...prev.data,
                footer: {
                    ...(prev.data?.footer ?? {}),
                    [key]: value,
                },
            },
        }));
    };
    
    const setChecklistAnswer = (sectionKey: string, index: number, value: StatusAnswer) => {
        setForm((prev) => {
            const current = Array.isArray(prev.data?.body?.[sectionKey])
                ? [...prev.data.body[sectionKey]]
                : [];

            current[index] = {
                ...current[index],
                answer: value,
            };

            return {
                ...prev,
                data: {
                    ...prev.data,
                    body: {
                        ...(prev.data?.body ?? {}),
                        [sectionKey]: current,
                    },
                },
            };
        });
    };

    const setChecklistRepaired = (sectionKey: string, index: number, checked: boolean) => {
        setForm((prev) => {
            const current = Array.isArray(prev.data?.body?.[sectionKey])
                ? [...prev.data.body[sectionKey]]
                : [];

            current[index] = {
                ...current[index],
                repaired: checked,
            };

            return {
                ...prev,
                data: {
                    ...prev.data,
                    body: {
                        ...(prev.data?.body ?? {}),
                        [sectionKey]: current,
                    },
                },
            };
        });
    };

    const deriveCompliance = () => {
        const rule = template?.compliance ?? {};
        const sources = Array.isArray(rule.sources) ? rule.sources : [];

        for (const source of sources) {
            const rows = Array.isArray(bodyData[source]) ? bodyData[source] : [];
            if (rows.some((row: any) => row.answer === 'fail')) {
                return false;
            }
        }

        return true;
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true);

        const payload = {
            ...form,
            compliant: deriveCompliance(),
        };

        router.put(route('service-reports.update', report.id), payload, {
            preserveScroll: true,
            onFinish: () => setSaving(false),
        });
    };

    const getChecklistRows = (section: TemplateSection) => {
        const existingRows = Array.isArray(bodyData[section.key]) ? bodyData[section.key] : [];
    
        if (existingRows.length > 0) {
            return existingRows;
        }
    
        return Array.isArray(section.rows) ? buildDefaultChecklistRows(section.rows) : [];
    };

    const renderSimpleField = (
        field: TemplateField,
        value: any,
        onChange: (value: any) => void,
        disabled = false
    ) => {
        const type = field.type;

        if (type === 'textarea') {
            return (
                <Form.Control
                    as="textarea"
                    rows={3}
                    value={value ?? ''}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.value)}
                />
            );
        }

        if (type === 'year_select') {
            const currentYear = new Date().getFullYear();
            const yearsBack = Number(field.years_back ?? 15);
            const years = Array.from({ length: yearsBack }, (_, i) => String(currentYear - i));

            return (
                <Form.Select
                    value={value ?? ''}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.value)}
                >
                    <option value="">Select year</option>
                    {years.map((year) => (
                        <option key={year} value={year}>
                            {year}
                        </option>
                    ))}
                </Form.Select>
            );
        }

        if (type === 'select') {
            return (
                <Form.Select
                    value={value ?? ''}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.value)}
                >
                    <option value="">Select</option>
                    {(field.options ?? []).map((option) => (
                        <option key={option.value} value={option.value}>
                            {option.label}
                        </option>
                    ))}
                </Form.Select>
            );
        }

        if (type === 'checkbox') {
            return (
                <Form.Check
                    type="checkbox"
                    checked={!!value}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.checked)}
                />
            );
        }

        if (type === 'multi_checkbox') {
            const currentValues = Array.isArray(value) ? value : [];

            return (
                <div className="d-flex flex-wrap gap-3">
                    {(field.options ?? []).map((option) => (
                        <Form.Check
                            key={option.value}
                            type="checkbox"
                            label={option.label}
                            checked={currentValues.includes(option.value)}
                            onChange={(e) => {
                                const nextValues = e.target.checked
                                    ? [...currentValues, option.value]
                                    : currentValues.filter((v: string) => v !== option.value);

                                onChange(nextValues);
                            }}
                        />
                    ))}
                </div>
            );
        }

        if (type === 'date') {
            return (
                <Form.Control
                    type="date"
                    value={toDateInput(value)}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.value)}
                />
            );
        }

        if (type === 'time') {
            return (
                <Form.Control
                    type="time"
                    value={toTimeInput(value)}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.value)}
                />
            );
        }

        if (type === 'number') {
            return (
                <Form.Control
                    type="number"
                    value={value ?? ''}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.value)}
                />
            );
        }

        if (type === 'calculated') {
            return <Form.Control type="text" value={value ?? ''} readOnly disabled />;
        }

        return (
            <Form.Control
                type="text"
                value={value ?? ''}
                disabled={disabled}
                onChange={(e) => onChange(e.target.value)}
            />
        );
    };

    const renderHeaderField = (field?: TemplateField) => {
        if (!field) return null;
        if (field.visible === false) return null;
        if (field.type === 'hidden') return null;

        if (field.key === 'owner_name') {
            const ownerName = (headerData.owner_name || headerData.owner_authorized_agent_name || '').trim();
            const selectedOwnerId = headerData.owner_contact_id || headerData.owner_authorized_agent_id || '';
            const showLegacyOwner = !selectedOwner && ownerName;
        
            return (
                <Col md={6} key={field.key}>
                    <Form.Group>
                        <Form.Label>{field.label}</Form.Label>
                        <Form.Select
                            value={selectedOwner?.id ?? (showLegacyOwner ? '__legacy_owner__' : selectedOwnerId)}
                            disabled={!form.account_id}
                            onChange={(e) => {
                                const raw = e.target.value;
        
                                if (raw === '__legacy_owner__') {
                                    return;
                                }
        
                                const id = Number(raw || 0);
                                const found = contactResults.find((c) => c.id === id) ?? null;
        
                                setSelectedOwner(found);
        
                                setHeaderField('owner_name', found?.label ?? '');
                                setHeaderField('owner_contact_id', found?.id ?? '');
        
                                // temporary GI compatibility
                                setHeaderField('owner_authorized_agent_name', found?.label ?? '');
                                setHeaderField('owner_authorized_agent_id', found?.id ?? '');
                            }}
                        >
                            <option value="">
                                {form.account_id ? 'Select owner / authorized agent' : 'Select an account first'}
                            </option>
        
                            {showLegacyOwner && (
                                <option value="__legacy_owner__">
                                    {ownerName} (archived)
                                </option>
                            )}
        
                            {contactResults.map((contact) => (
                                <option key={contact.id} value={contact.id}>
                                    {contact.label}
                                </option>
                            ))}
                        </Form.Select>
                    </Form.Group>
                </Col>
            );
        }

    if (field.key === 'ahj_name') {
            return (
                <Col md={6} key={field.key}>
                    <Form.Group>
                        <Form.Label>{field.label}</Form.Label>
                        <Form.Select
                            value={headerData.ahj_contact_id || ''}
                            disabled={!form.account_id}
                            onChange={(e) => {
                                const id = Number(e.target.value || 0);
                                const found = contactResults.find((c) => c.id === id) ?? null;
                                setHeaderField('ahj_name', found?.label ?? '');
                                setHeaderField('ahj_contact_id', found?.id ?? '');
                            }}
                        >
                            <option value="">
                                {form.account_id ? 'Select AHJ' : 'Select an account first'}
                            </option>
                            {contactResults.map((contact) => (
                                <option key={contact.id} value={contact.id}>
                                    {contact.label}
                                </option>
                            ))}
                        </Form.Select>
                    </Form.Group>
                </Col>
            );
        }        

        if (field.key === 'technician_name') {
            return (
                <Col md={6} key={field.key}>
                    <Form.Group>
                        <Form.Label>{field.label}</Form.Label>
        
                        <Form.Select
                            value={headerData.technician_contact_id || ''}
                            onChange={(e) => {
                                const id = Number(e.target.value || 0);
                                const found = technicianResults.find((c) => c.id === id) ?? null;
        
                                setSelectedTechnician(found);
        
                                setHeaderField('technician_name', found?.label ?? '');
                                setHeaderField('technician_contact_id', found?.id ?? '');
                            }}
                        >
                            <option value="">Select technician</option>
        
                            {technicianResults.map((tech) => (
                                <option key={tech.id} value={tech.id}>
                                    {tech.label}
                                </option>
                            ))}
                        </Form.Select>
                    </Form.Group>
                </Col>
            );
        }

        return (
            <Col md={6} key={field.key}>
                <Form.Group>
                    <Form.Label>{field.label}</Form.Label>
                    {renderSimpleField(field, headerData[field.key] ?? '', (value) => {
                        setHeaderField(field.key, value);

                        if (field.key === 'service_date') {
                            setRootField('service_date', value);
                        }
                    })}
                </Form.Group>
            </Col>
        );
    };

    const renderFieldsSection = (section: TemplateSection) => {
        const sectionData = ((bodyData[section.key] ?? {}) as Record<string, any>);
    
        if (section.key === 'equipment_details') {
            const normalFields = (section.fields ?? []).filter(
                (field) => field.key !== 'fuel_other' && field.key !== 'cooking_equipment_other'
            );
    
            const showFuelOther =
                Array.isArray(sectionData.fuel) && sectionData.fuel.includes('other');
    
            const showCookingOther =
                Array.isArray(sectionData.cooking_equipment) && sectionData.cooking_equipment.includes('other');
    
            const fuelOtherField = (section.fields ?? []).find((field) => field.key === 'fuel_other');
            const cookingOtherField = (section.fields ?? []).find((field) => field.key === 'cooking_equipment_other');
    
            return (
                <Card className="gd-form-card mb-4" key={section.key}>
                    <Card.Body>
                        <h5 className="mb-3">{section.label}</h5>
                        <Row className="g-3">
                            {normalFields.map((field) => (
                                <Col
                                    md={field.type === 'textarea' ? 12 : field.type === 'checkbox' ? 3 : 6}
                                    key={`${section.key}-${field.key}`}
                                >
                                    <Form.Group>
                                        <Form.Label>{field.label}</Form.Label>
                                        {renderSimpleField(
                                            field,
                                            sectionData[field.key] ?? '',
                                            (value) => setBodyField(section.key, field.key, value)
                                        )}
                                    </Form.Group>
    
                                    {field.key === 'fuel' && showFuelOther && fuelOtherField && (
                                        <Form.Group className="mt-3">
                                            <Form.Label>{fuelOtherField.label}</Form.Label>
                                            {renderSimpleField(
                                                fuelOtherField,
                                                sectionData[fuelOtherField.key] ?? '',
                                                (value) => setBodyField(section.key, fuelOtherField.key, value)
                                            )}
                                        </Form.Group>
                                    )}
    
                                    {field.key === 'cooking_equipment' && showCookingOther && cookingOtherField && (
                                        <Form.Group className="mt-3">
                                            <Form.Label>{cookingOtherField.label}</Form.Label>
                                            {renderSimpleField(
                                                cookingOtherField,
                                                sectionData[cookingOtherField.key] ?? '',
                                                (value) => setBodyField(section.key, cookingOtherField.key, value)
                                            )}
                                        </Form.Group>
                                    )}
                                </Col>
                            ))}
                        </Row>
                    </Card.Body>
                </Card>
            );
        }
    
        return (
            <Card className="gd-form-card mb-4" key={section.key}>
                <Card.Body>
                    <h5 className="mb-3">{section.label}</h5>
                    <Row className="g-3">
                        {(section.fields ?? []).map((field) => (
                            <Col
                                md={field.type === 'textarea' ? 12 : field.type === 'checkbox' ? 3 : 6}
                                key={`${section.key}-${field.key}`}
                            >
                                <Form.Group>
                                    <Form.Label>{field.label}</Form.Label>
                                    {renderSimpleField(
                                        field,
                                        sectionData[field.key] ?? '',
                                        (value) => setBodyField(section.key, field.key, value)
                                    )}
                                </Form.Group>
                            </Col>
                        ))}
                    </Row>
                </Card.Body>
            </Card>
        );
    };   

    const renderGroupedFieldsSection = (section: TemplateSection) => (
        <Card className="gd-form-card mb-4" key={section.key}>
            <Card.Body>
                <h5 className="mb-3">{section.label}</h5>

                {(section.groups ?? []).map((group, groupIndex) => (
                    <div
                        key={`${section.key}-${group.key}`}
                        className={groupIndex > 0 ? 'pt-3 mt-3 border-top' : ''}
                    >
                        <h5 className="mb-3">{group.label}</h5>

                        <Row className="g-3">
                            {group.fields.map((field) => (
                                <Col
                                    md={field.type === 'textarea' ? 12 : field.type === 'checkbox' ? 3 : 6}
                                    key={`${group.key}-${field.key}`}
                                >
                                    <Form.Group>
                                        <Form.Label>{field.label}</Form.Label>
                                        {renderSimpleField(
                                            field,
                                            (((bodyData[section.key] ?? {})[group.key] ?? {}) as any)[field.key] ?? '',
                                            (value) => setGroupedField(section.key, group.key, field.key, value)
                                        )}
                                    </Form.Group>
                                </Col>
                            ))}
                        </Row>
                    </div>
                ))}
            </Card.Body>
        </Card>
    );

    const renderRepeatableTextSection = (section: TemplateSection) => {
        const minItems = section.min_items ?? 1;
        const maxItems = section.max_items ?? 10;
        const itemLabel = section.item_label ?? 'Item';

        let items = Array.isArray(bodyData[section.key]) ? bodyData[section.key] : [];
        if (items.length === 0) {
            items = Array.from({ length: minItems }, () => '');
        }

        const setItems = (nextItems: string[]) => {
            setForm((prev) => ({
                ...prev,
                data: {
                    ...prev.data,
                    body: {
                        ...(prev.data?.body ?? {}),
                        [section.key]: nextItems,
                    },
                },
            }));
        };

        return (
            <Card className="gd-form-card mb-4" key={section.key}>
                <Card.Body>
                    <div className="mb-3">
                        <h5 className="mb-0">{section.label}</h5>
                    </div>

                    <Row className="g-3">
                        {items.map((value: string, index: number) => (
                            <Col md={6} key={`${section.key}-${index}`}>
                                <Form.Group>
                                    <Form.Label>{itemLabel} {index + 1}</Form.Label>
                                    <Form.Control
                                        type="text"
                                        value={value}
                                        onChange={(e) => {
                                            const next = [...items];
                                            next[index] = e.target.value;
                                            setItems(next);
                                        }}
                                    />
                                </Form.Group>
                            </Col>
                        ))}
                    </Row>

                    <div className="mt-3 d-flex">
                        <Button
                            type="button"
                            variant="outline-primary"
                            size="sm"
                            className="px-3"
                            onClick={() => {
                                if (items.length >= maxItems) return;
                                setItems([...items, '']);
                            }}
                        >
                            + Add Appliance
                        </Button>
                    </div>
                </Card.Body>
            </Card>
        );
    };

    const renderChecklistSection = (section: TemplateSection) => {
        const rows = getChecklistRows(section);

        return (
            <Card className="gd-form-card mb-4" key={section.key}>
                <Card.Body>
                    <h5 className="mb-3">{section.label}</h5>

                    <div className="table-responsive">
                        <table className="table table-sm align-middle">
                            <thead>
                                <tr>
                                    <th>Question</th>
                                    <th style={{ width: '60px', textAlign: 'center' }}>Pass</th>
                                    <th style={{ width: '60px', textAlign: 'center' }}>Fail</th>
                                    <th style={{ whiteSpace: 'nowrap', width: '70px', textAlign: 'center' }}>
                                        N/A
                                    </th>
                                    <th style={{ width: '80px', textAlign: 'center' }}>Repaired</th>
                                </tr>
                            </thead>
                            <tbody>
                                {rows.map((row: any, index: number) => (
                                    <tr key={row.key ?? index}>
                                        <td>{row.label}</td>
                                        <td className="text-center">
                                            <Form.Check
                                                type="radio"
                                                name={`${section.key}-${index}`}
                                                checked={row.answer === 'pass'}
                                                onChange={() => setChecklistAnswer(section.key, index, 'pass')}
                                            />
                                        </td>
                                        <td className="text-center">
                                            <Form.Check
                                                type="radio"
                                                name={`${section.key}-${index}`}
                                                checked={row.answer === 'fail'}
                                                onChange={() => setChecklistAnswer(section.key, index, 'fail')}
                                            />
                                        </td>
                                        <td className="text-center">
                                            <Form.Check
                                                type="radio"
                                                name={`${section.key}-${index}`}
                                                checked={row.answer === 'na'}
                                                onChange={() => setChecklistAnswer(section.key, index, 'na')}
                                            />
                                        </td>
                                        <td className="text-center">
                                            <Form.Check
                                                type="checkbox"
                                                checked={!!row.repaired}
                                                onChange={(e) => setChecklistRepaired(section.key, index, e.target.checked)}
                                            />
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    {!!section.extra_fields?.length && (
                        <Row className="g-3 mt-1">
                            {section.extra_fields.map((field) => (
                                <Col md={6} key={`${section.key}-${field.key}`}>
                                    <Form.Group>
                                        <Form.Label>{field.label}</Form.Label>
                                        {renderSimpleField(
                                            field,
                                            (bodyData[section.key] ?? {})[field.key] ?? '',
                                            (value) => setBodyField(section.key, field.key, value)
                                        )}
                                    </Form.Group>
                                </Col>
                            ))}
                        </Row>
                    )}
                </Card.Body>
            </Card>
        );
    };

    const renderBodySection = (section: TemplateSection) => {
        if (section.type === 'fields') return renderFieldsSection(section);
        if (section.type === 'grouped_fields') return renderGroupedFieldsSection(section);
        if (section.type === 'checklist') return renderChecklistSection(section);
        if (section.type === 'repeatable_text') return renderRepeatableTextSection(section);
        if (section.type === 'repeatable_grouped') return renderRepeatableGroupedSection(section);
        if (section.type === 'repeatable_grouped_devices') return renderRepeatableGroupedDevicesSection(section);
        return null;
    };
    
    const renderRepeatableGroupedDevicesSection = (section: TemplateSection) => {
        const groups = Array.isArray(bodyData[section.key]) ? bodyData[section.key] : [];
    
        const setGroups = (nextGroups: any[]) => {
            setForm((prev) => ({
                ...prev,
                data: {
                    ...prev.data,
                    body: {
                        ...(prev.data?.body ?? {}),
                        [section.key]: nextGroups,
                    },
                },
            }));
        };
    
        const addLocation = () => {
            const next = [
                ...groups,
                {
                    location_name: '',
                    devices: [],
                },
            ];
            setGroups(next);
        };
    
        const updateLocationName = (groupIndex: number, value: string) => {
            const next = [...groups];
            next[groupIndex] = {
                ...next[groupIndex],
                location_name: value,
            };
            setGroups(next);
        };
    
        const removeLocation = (groupIndex: number) => {
            const next = [...groups];
            next.splice(groupIndex, 1);
            setGroups(next);
        };
    
        const addDevice = (groupIndex: number) => {
            const next = [...groups];
            const devices = Array.isArray(next[groupIndex]?.devices) ? [...next[groupIndex].devices] : [];
    
            devices.push({
                device: '',
                sub_location: '',
                a: false,
                b: false,
                c: false,
                d: false,
                e: '',
                f: false,
                comments: '',
            });
    
            next[groupIndex] = {
                ...next[groupIndex],
                devices,
            };
    
            setGroups(next);
        };
    
        const updateDeviceField = (groupIndex: number, deviceIndex: number, fieldKey: string, value: any) => {
            const next = [...groups];
            const devices = Array.isArray(next[groupIndex]?.devices) ? [...next[groupIndex].devices] : [];
    
            devices[deviceIndex] = {
                ...devices[deviceIndex],
                [fieldKey]: value,
            };
    
            next[groupIndex] = {
                ...next[groupIndex],
                devices,
            };
    
            setGroups(next);
        };
    
        const removeDevice = (groupIndex: number, deviceIndex: number) => {
            const next = [...groups];
            const devices = Array.isArray(next[groupIndex]?.devices) ? [...next[groupIndex].devices] : [];
    
            devices.splice(deviceIndex, 1);
    
            next[groupIndex] = {
                ...next[groupIndex],
                devices,
            };
    
            setGroups(next);
        };
    
        const deviceOptions = Array.isArray((section as any).device_options) ? (section as any).device_options : [];
    
        return (
            <Card className="gd-form-card mb-4" key={section.key}>
                <Card.Body>
                    <h5 className="mb-3">{section.label}</h5>
    
                    {groups.map((group: any, groupIndex: number) => (
                        <div key={`${section.key}-group-${groupIndex}`} className="border rounded p-3 mb-4">
                            <Row className="g-3 align-items-end mb-3">
                                <Col md={8}>
                                    <Form.Group>
                                        <Form.Label>{(section as any).location_label || 'Location'}</Form.Label>
                                        <Form.Control
                                            type="text"
                                            value={group.location_name ?? ''}
                                            onChange={(e) => updateLocationName(groupIndex, e.target.value)}
                                            placeholder="Main floor"
                                        />
                                    </Form.Group>
                                </Col>
                                <Col md={4} className="text-md-end">
                                    <Button
                                        type="button"
                                        variant="outline-danger"
                                        size="sm"
                                        onClick={() => removeLocation(groupIndex)}
                                    >
                                        Remove Location
                                    </Button>
                                </Col>
                            </Row>
    
                            {(Array.isArray(group.devices) ? group.devices : []).map((device: any, deviceIndex: number) => (
                                <div key={`${section.key}-group-${groupIndex}-device-${deviceIndex}`} className="border rounded p-3 mb-3">
                                    <Row className="g-3">
                                        <Col md={4}>
                                            <Form.Group>
                                                <Form.Label>{(section as any).device_label || 'Device'}</Form.Label>
                                                <Form.Select
                                                    value={device.device ?? ''}
                                                    onChange={(e) =>
                                                        updateDeviceField(groupIndex, deviceIndex, 'device', e.target.value)
                                                    }
                                                >
                                                    <option value="">Select device</option>
                                                    {deviceOptions.map((option: any) => (
                                                        <option key={option.value} value={option.value}>
                                                            {option.label}
                                                        </option>
                                                    ))}
                                                </Form.Select>
                                            </Form.Group>
                                        </Col>
    
                                        <Col md={4}>
                                            <Form.Group>
                                                <Form.Label>Sub-location</Form.Label>
                                                <Form.Control
                                                    type="text"
                                                    value={device.sub_location ?? ''}
                                                    onChange={(e) =>
                                                        updateDeviceField(groupIndex, deviceIndex, 'sub_location', e.target.value)
                                                    }
                                                    placeholder="Main electrical closet"
                                                />
                                            </Form.Group>
                                        </Col>
    
                                        <Col md={4}>
                                            <Form.Group>
                                                <Form.Label>E (Zone / Address)</Form.Label>
                                                <Form.Control
                                                    type="text"
                                                    value={device.e ?? ''}
                                                    onChange={(e) =>
                                                        updateDeviceField(groupIndex, deviceIndex, 'e', e.target.value)
                                                    }
                                                    placeholder="3"
                                                />
                                            </Form.Group>
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label="A"
                                                checked={!!device.a}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'a', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label="B"
                                                checked={!!device.b}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'b', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label="C"
                                                checked={!!device.c}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'c', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label="D"
                                                checked={!!device.d}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'd', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label="F"
                                                checked={!!device.f}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'f', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={12}>
                                            <Form.Group>
                                                <Form.Label>Comments</Form.Label>
                                                <Form.Control
                                                    type="text"
                                                    value={device.comments ?? ''}
                                                    onChange={(e) =>
                                                        updateDeviceField(groupIndex, deviceIndex, 'comments', e.target.value)
                                                    }
                                                />
                                            </Form.Group>
                                        </Col>
    
                                        <Col md={12}>
                                            <Button
                                                type="button"
                                                variant="outline-danger"
                                                size="sm"
                                                onClick={() => removeDevice(groupIndex, deviceIndex)}
                                            >
                                                Remove Device
                                            </Button>
                                        </Col>
                                    </Row>
                                </div>
                            ))}
    
                            <Button
                                type="button"
                                variant="outline-primary"
                                size="sm"
                                onClick={() => addDevice(groupIndex)}
                            >
                                {(section as any).add_device_label || 'Add Device'}
                            </Button>
                        </div>
                    ))}
    
                    <Button
                        type="button"
                        variant="primary"
                        size="sm"
                        onClick={addLocation}
                    >
                        {(section as any).add_location_label || 'Add Location'}
                    </Button>
                </Card.Body>
            </Card>
        );
    };    

    const renderFooterField = (field: TemplateField) => {
        if (field.visible === false) return null;

        return (
            <Col md={field.type === 'textarea' ? 12 : 6} key={field.key}>
                <Form.Group>
                    <Form.Label>{field.label}</Form.Label>
                    {renderSimpleField(
                        field,
                        footerData[field.key] ?? '',
                        (value) => setFooterField(field.key, value),
                        field.key === 'disclaimer_text'
                    )}                    
                </Form.Group>
            </Col>
        );
    };

    return (
        <MainLayout>
            <Head title="Edit Service Report" />

            <div className="gd-account-show-page gd-page-edit service-reports-page">
                <div className="d-flex justify-content-between align-items-center mb-3">
                    <h4 className="mb-0">Service Reports</h4>
                    <div className="d-flex gap-2">
                        <Link href={route('service-reports.index')} className="btn btn-outline-secondary">
                            Back
                        </Link>
                    </div>
                </div>

                <div className="account-header-bar d-flex align-items-center justify-content-between">
                    <div className="d-flex align-items-center gap-3">
                        <div className="gd-appointment-hero__icon">
                            <i className="ti ti-file-description" />
                        </div>
                        <div>
                            <div className="text-white fw-semibold">
                                {report.account
                                    ? `${report.account.company_name}${report.account.suffix ? ` (${report.account.suffix})` : ''}`
                                    : '—'}
                            </div>
                            <div className="text-white-50 small">{report.type_label || report.template_key || '—'}</div>
                        </div>
                    </div>

                    <div className="text-end">
                        <div className="text-white-50 small">Report #</div>
                        <div className="text-white fw-semibold">{report.report_number || report.id}</div>
                    </div>
                </div>

                <Card className="gd-form-card gd-subcard border-0 rounded-top-0 shadow-sm">
                    <Card.Body>
                        <Form onSubmit={handleSubmit}>
                            <Card className="gd-form-card mb-4">
                                <Card.Body>
                                    <h5 className="mb-3">Service Information</h5>
                                    <Row className="g-3">
                                        {template.header.fields.map((field) => renderHeaderField(field))}
                                    </Row>
                                </Card.Body>
                            </Card>

                            {template.body.sections.map((section) => renderBodySection(section))}

                            <Card className="gd-form-card mb-4">
                                <Card.Body>
                                    <h5 className="mb-3">Notes & Final Details</h5>
                                    <Row className="g-3">
                                        {template.footer.fields.map((field) => renderFooterField(field))}
                                    </Row>
                                </Card.Body>
                            </Card>

                            <div className="d-flex justify-content-between align-items-end flex-wrap gap-3">
                                {report.status !== 'final' ? (
                                    <div style={{ minWidth: '220px' }}>
                                        <Form.Group>
                                            <Form.Label>Status</Form.Label>
                                            <Form.Select
                                                value={form.status}
                                                onChange={(e) => setRootField('status', e.target.value)}
                                            >
                                                <option value="draft">Draft</option>
                                                <option value="final">Final</option>
                                            </Form.Select>
                                        </Form.Group>
                                    </div>
                                ) : <div />}

                                <div className="d-flex gap-2">
                                    <Button type="submit" disabled={saving}>
                                        {saving ? 'Saving...' : 'Update Service Report'}
                                    </Button>

                                    <Link href={route('service-reports.index')} className="btn btn-outline-secondary">
                                        Cancel
                                    </Link>
                                </div>
                            </div>
                        </Form>
                    </Card.Body>
                </Card>
            </div>
        </MainLayout>
    );
}