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[];
};

type PageProps = {
    mode: 'create';
    title: string;
    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>;
        last_service_date?: string | null;
    };
    suggested_report_number: string;
    report: null;
    auth?: {
        user?: {
            id?: number;
            name?: string;
            email?: string;
        };
    };

    prefill_account?: {
        id: number;
        company_name: string;
        suffix?: string | null;
    } | null;

    prefill_contacts?: Array<{
        id: number;
        name: string;
    }>;

    prefill?: {
        account_id?: number | null;
        last_service_date?: string | null;
    } | null;
};

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

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

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

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;
};

    const buildDefaultChecklistRows = (sectionKey: string, rows: Array<{ key: string; label: string }>) => {
        let defaultAnswer: StatusAnswer = '';
    
        if (sectionKey === 'inspections' || sectionKey === 'semi_annual_inspection') {
            defaultAnswer = 'pass';
        }
    
        if (sectionKey === 'maintenance_and_hydrostatic') {
            defaultAnswer = 'na';
        }
    
        return rows.map((row) => ({
            key: row.key,
            label: row.label,
            answer: defaultAnswer,
            repaired: false,
        }));
    };    
    
    const getTodayLocalDate = (): string => {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };
    
    const getRoundedHourDefaults = (): { start: string; end: string } => {
        const now = new Date();
    
        const start = new Date(now);
        start.setMinutes(0, 0, 0);
    
        const end = new Date(start);
        end.setHours(end.getHours() + 1);
    
        const toTime = (d: Date): string => {
            const hours = String(d.getHours()).padStart(2, '0');
            const minutes = String(d.getMinutes()).padStart(2, '0');
            return `${hours}:${minutes}`;
        };
    
        return {
            start: toTime(start),
            end: toTime(end),
        };
    };
    
    export default function ServiceReportsCreate() {
    const { props } = usePage<PageProps>();
    const { title } = props;
    const {
        template,
        default_data,
        suggested_report_number,
        auth,
        prefill_account,
        prefill_contacts,
        prefill,
    } = props as any;
    
    console.log('prefill_account', prefill_account);
    console.log('prefill_contacts', prefill_contacts);
    console.log('prefill', prefill);

    const last_service_date = default_data?.last_service_date ?? null;
    
    const accountDisplayName = prefill_account
        ? `${prefill_account.company_name}${prefill_account.suffix ? ` (${prefill_account.suffix})` : ''}`
        : '';
    
    const currentTemplateLabel =
        template.key === 'ke'
            ? 'Kitchen Exhaust Report'
            : template.key === 'fs'
                ? 'Fire Suppression Report'
                : template.key === 'gi'
                    ? 'Grease Interceptor Report'
                    : template.key === 'pe'
                        ? 'Portable Extinguishers & Emergency Lights Report'
                        : template.key === 'fa'
                            ? 'Fire Alarm Report'
                            : title;    

    const initialData = useMemo(() => {
        const today = getTodayLocalDate();
        const { start, end } = getRoundedHourDefaults();
    
        const baseData = JSON.parse(
            JSON.stringify(
                default_data ?? {
                    header: {},
                    body: {},
                    footer: {},
                    meta: {},
                }
            )
        );
    
        baseData.header = {
            ...(baseData.header ?? {}),
            service_date: baseData.header?.service_date || today,
            start_time: baseData.header?.start_time || start,
            end_time: baseData.header?.end_time || end,
            last_service_date:
                template.key === 'pe'
                    ? (baseData.header?.last_service_date || last_service_date || '')
                    : (baseData.header?.last_service_date || ''),
        };
    
        // Seed checklist defaults into actual form state
        const sections = template?.body?.sections ?? [];
        const nextBody = { ...(baseData.body ?? {}) };
    
        sections.forEach((section: TemplateSection) => {
            if (section.type === 'checklist' && Array.isArray(section.rows)) {
                const existingRows = Array.isArray(nextBody[section.key]) ? nextBody[section.key] : [];
                const seededRows = buildDefaultChecklistRows(section.key, section.rows);
        
                nextBody[section.key] =
                    existingRows.length > 0
                        ? existingRows.map((row: any, index: number) => ({
                              key: row?.key ?? seededRows[index]?.key ?? '',
                              label: row?.label ?? seededRows[index]?.label ?? '',
                              answer: row?.answer || seededRows[index]?.answer || '',
                              repaired: typeof row?.repaired === 'boolean' ? row.repaired : false,
                          }))
                        : seededRows;
            }
        });
    
        baseData.body = nextBody;
    
        return {
            account_id: prefill?.account_id ?? '',
            service_id: '',
            service_date: today,
            report_number: suggested_report_number ?? '',
            status: 'draft',
            compliant: true,
            template_key: template.key,
            type:
                template.key === 'fs'
                    ? 'Fire Suppression'
                    : template.key === 'ke'
                        ? 'Kitchen Exhaust Hood Cleaning'
                        : template.key === 'pe'
                            ? 'Portable Extinguishers & Emergency Lights'
                            : template.key,
            data: baseData,
        };
            }, [template, default_data, suggested_report_number, prefill, last_service_date]);

    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 [showNewMenu, setShowNewMenu] = useState(false);
    const [accountQuery, setAccountQuery] = useState('');
    const [accountResults, setAccountResults] = useState<AccountOption[]>([]);
    const [selectedAccount, setSelectedAccount] = useState<AccountOption | null>(
        prefill_account
            ? {
                  id: prefill_account.id,
                  label:
                      prefill_account.company_name +
                      (prefill_account.suffix ? ` (${prefill_account.suffix})` : ''),
              }
            : null
    );
    const [showAccountResults, setShowAccountResults] = useState(false);

    const [contactResults, setContactResults] = useState<ContactOption[]>([]);

    const [technicianResults, setTechnicianResults] = useState<ContactOption[]>([]);
    const [selectedTechnician, setSelectedTechnician] = useState<ContactOption | null>(null);

    const calculateTotalHours = (start: string, end: string): string => {
        if (!start || !end) return '';

        const [startHour, startMinute] = start.split(':').map(Number);
        const [endHour, endMinute] = end.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;
        }

        const diffMinutes = endTotal - startTotal;
        const hours = diffMinutes / 60;

        return hours.toFixed(1);
    };

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

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

    useEffect(() => {
        const clean = (value: string) =>
            (value || '')
                .toLowerCase()
                .replace(/[^a-z0-9\s]/g, ' ')
                .replace(/\s+/g, ' ')
                .trim();
    
        const firstLast = (value: string) => {
            const parts = clean(value).split(' ').filter(Boolean);
            if (parts.length === 0) return '';
            if (parts.length === 1) return parts[0];
            return `${parts[0]} ${parts[parts.length - 1]}`;
        };
    
        if (!technicianResults.length) return;
        if (headerData.technician_contact_id) return;
    
        const currentUserName = auth?.user?.name || '';
        const currentUserFirstLast = firstLast(currentUserName);
    
        const found =
            (currentUserFirstLast
                ? technicianResults.find((tech) => firstLast(tech.label) === currentUserFirstLast) ||
                  technicianResults.find((tech) => clean(tech.label) === clean(currentUserName)) ||
                  technicianResults.find((tech) => clean(tech.label).includes(currentUserFirstLast))
                : null) ??
            technicianResults[0] ??
            null;
    
        if (found) {
            setSelectedTechnician(found);
            setHeaderField('technician_name', found.label);
            setHeaderField('technician_contact_id', found.id);
        }
    }, [auth?.user?.name, technicianResults, headerData.technician_contact_id]);

    useEffect(() => {
        const q = accountQuery.trim();

        if (q.length < 2) {
            setAccountResults([]);
            setShowAccountResults(false);
            return;
        }

        const timer = setTimeout(() => {
            fetch(route('accounts.search') + `?q=${encodeURIComponent(q)}`, {
                headers: { Accept: 'application/json' },
            })
                .then((res) => res.json())
                .then((data) => {
                    const rows = Array.isArray(data) ? data : [];
                    setAccountResults(rows);
                    setShowAccountResults(rows.length > 0);
                })
                .catch(() => {
                    setAccountResults([]);
                    setShowAccountResults(false);
                });
        }, 250);

        return () => clearTimeout(timer);
    }, [accountQuery]);

    useEffect(() => {
        if (prefill_account?.id && prefill_contacts?.length) {
            console.log('using prefill_contacts', prefill_contacts);
    
            setContactResults(
                prefill_contacts.map((c: any) => ({
                    id: c.id,
                    label: c.name,
                }))
            );
            return;
        }
    
        const accountId = form.account_id;
    
        if (!accountId) {
            setContactResults([]);
            return;
        }
    
        console.log('fetching contacts for account', accountId);
    
        fetch(route('contacts.by-account') + `?account_id=${accountId}`, {
            headers: { Accept: 'application/json' },
        })
            .then((res) => res.json())
            .then((data) => {
                console.log('contacts.by-account returned', data);
                setContactResults(Array.isArray(data) ? data : []);
            })
            .catch((err) => {
                console.error('contacts.by-account failed', err);
                setContactResults([]);
            });
    }, [form.account_id, prefill_account, prefill_contacts]);
    
    useEffect(() => {
        if (!contactResults.length) return;
    
        const currentOwnerId = Number(headerData.owner_contact_id || 0);
    
        const firstContact = contactResults[0] ?? null;
        
        const currentAhjId = Number(headerData.ahj_contact_id || 0);
        
        if (!currentAhjId && firstContact) {
            setHeaderField('ahj_contact_id', firstContact.id);
            setHeaderField('ahj_name', firstContact.label);
        }        
    
        if (!currentOwnerId && firstContact) {
            setHeaderField('owner_contact_id', firstContact.id);
            setHeaderField('owner_name', firstContact.label);
    
            // keep GI compatibility keys in sync
            setHeaderField('owner_authorized_agent_id', firstContact.id);
            setHeaderField('owner_authorized_agent_name', firstContact.label);
        }
    }, [contactResults]);    

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

    const setRootField = (key: string, value: any) => {
        setForm((prev) => ({
            ...prev,
            [key]: value,
        }));
    };
    
    const LegendHint = ({ text }: { text: string }) => (
        <span
            title={text}
            style={{
                display: 'inline-block',
                marginLeft: '6px',
                cursor: 'help',
                color: '#6c757d',
                fontSize: '12px',
                border: '1px solid #adb5bd',
                borderRadius: '50%',
                width: '16px',
                height: '16px',
                lineHeight: '14px',
                textAlign: 'center',
                userSelect: 'none',
            }}
        >
            ?
        </span>
    );    
    
    const FA_LEGEND = {
        A: 'Correctly installed',
        B: 'Requires service, repairs, missing, or cleaning',
        C: 'Alarm operation confirmed',
        D: 'Annunciator indication confirmed',
        E: 'Zone circuit number or address',
        F: 'Smoke detector sensitivity testing',
    };    
    
    useEffect(() => {
        if (!prefill_account) return;
    
        setSelectedAccount({
            id: prefill_account.id,
            label:
                prefill_account.company_name +
                (prefill_account.suffix ? ` (${prefill_account.suffix})` : ''),
        });
    
        setRootField('account_id', prefill_account.id);
    }, [prefill_account]);  

    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.post(route('service-reports.store'), payload, {
            preserveScroll: true,
            onFinish: () => setSaving(false),
        });
    };

    const getChecklistRows = (section: TemplateSection) => {
        return Array.isArray(bodyData[section.key]) ? bodyData[section.key] : [];
    };

    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 === '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 === 'year_select') {
            const currentYear = new Date().getFullYear();
            const yearsBack = Number((field as any).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 === 'status_radio') {
            return (
                <div className="d-flex flex-wrap gap-3 pt-1">
                    <Form.Check inline type="radio" label="Pass" name={field.key} checked={value === 'pass'} onChange={() => onChange('pass')} />
                    <Form.Check inline type="radio" label="Fail" name={field.key} checked={value === 'fail'} onChange={() => onChange('fail')} />
                    <Form.Check inline type="radio" label="N/A" name={field.key} checked={value === 'na'} onChange={() => onChange('na')} />
                </div>
            );
        }        

        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={value ?? ''}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.value)}
                />
            );
        }

        if (type === 'time') {
            return (
                <Form.Control
                    type="time"
                    value={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 === 'last_service_date' && template.key === 'pe') {
            const hasPreviousPe = !!lastPeServiceDate;
    
            return (
                <Col md={6} key={field.key}>
                    <Form.Group>
                        <Form.Label>{field.label}</Form.Label>
                        <Form.Control
                            type="date"
                            value={headerData[field.key] ?? ''}
                            readOnly={hasPreviousPe}
                            disabled={hasPreviousPe}
                            className={hasPreviousPe ? 'bg-light text-muted' : ''}
                            onChange={(e) => {
                                if (!hasPreviousPe) {
                                    setHeaderField(field.key, e.target.value);
                                }
                            }}
                        />
                        {!hasPreviousPe && (
                            <Form.Text className="text-muted">
                                Optional — use for first account service if no prior PE report exists.
                            </Form.Text>
                        )}
                    </Form.Group>
                </Col>
            );
        }
    
        if (field.key === 'owner_name') {
            return (
                <Col md={6} key={field.key}>
                    <Form.Group>
                        <Form.Label>{field.label}</Form.Label>
                        <Form.Select
                            value={headerData.owner_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('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>
                            {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 [lastPeServiceDate, setLastPeServiceDate] = useState<string | null>(
        default_data?.last_service_date ?? null
    );

    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 className="text-center text-success">Pass</th>
                                    <th className="text-center text-danger">Fail</th>
                                    <th style={{ whiteSpace: 'nowrap', width: '70px', textAlign: 'center' }}>N/A</th>
                                    <th className="text-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) <LegendHint text={FA_LEGEND.E} />
                                                </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={12}>
                                            <div className="small text-muted border rounded px-3 py-2 bg-light">
                                                <strong>A:</strong> {FA_LEGEND.A}
                                                {' '}|{' '}
                                                <strong>B:</strong> {FA_LEGEND.B}
                                                {' '}|{' '}
                                                <strong>C:</strong> {FA_LEGEND.C}
                                                {' '}|{' '}
                                                <strong>D:</strong> {FA_LEGEND.D}
                                                {' '}|{' '}
                                                <strong>E:</strong> {FA_LEGEND.E}
                                                {' '}|{' '}
                                                <strong>F:</strong> {FA_LEGEND.F}
                                            </div>
                                        </Col>                                        
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label={
                                                    <span>
                                                        A <LegendHint text={FA_LEGEND.A} />
                                                    </span>
                                                }
                                                checked={!!device.a}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'a', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label={
                                                    <span>
                                                        B <LegendHint text={FA_LEGEND.B} />
                                                    </span>
                                                }
                                                checked={!!device.b}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'b', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label={
                                                    <span>
                                                        C <LegendHint text={FA_LEGEND.C} />
                                                    </span>
                                                }
                                                checked={!!device.c}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'c', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label={
                                                    <span>
                                                        D <LegendHint text={FA_LEGEND.D} />
                                                    </span>
                                                }
                                                checked={!!device.d}
                                                onChange={(e) =>
                                                    updateDeviceField(groupIndex, deviceIndex, 'd', e.target.checked)
                                                }
                                            />
                                        </Col>
    
                                        <Col md={2}>
                                            <Form.Check
                                                type="checkbox"
                                                label={
                                                    <span>
                                                        F <LegendHint text={FA_LEGEND.F} />
                                                    </span>
                                                }
                                                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="Create Service Report" />

            <div className="gd-account-show-page gd-page-edit service-reports-page">
                <div className="page-title-head d-flex align-items-sm-center flex-sm-row flex-column mb-3">
                    <div className="flex-grow-1 mb-2 mb-sm-0">
                        <h4 className="fs-18 fw-semibold m-0">Create Service Report</h4>
                    </div>
                
                    <div className="mt-0 mt-sm-0">
                        <div className="d-flex gap-2">
                        <div
                            className="position-relative"
                            style={{ overflow: 'visible', zIndex: 2000 }}
                        >
                            <button
                                className="btn btn-gd-primary dropdown-toggle"
                                type="button"
                                onClick={() => {
                                    console.log('NEW MENU CLICKED');
                                    setShowNewMenu((prev) => !prev);
                                }}
                                aria-expanded={showNewMenu}
                            >
                                New
                            </button>
                        
                            {showNewMenu && (
                                <div
                                    className="dropdown-menu show"
                                    style={{
                                        position: 'absolute',
                                        top: '100%',
                                        left: 0,
                                        zIndex: 3000,
                                        minWidth: '310px',
                                        display: 'block',
                                    }}
                                >
                                    <Link
                                        href={route('service-reports.create', {
                                            template: 'ke',
                                            ...(prefill_account?.id ? { account_id: prefill_account.id } : {}),
                                        })}
                                        className="dropdown-item"
                                        onClick={() => setShowNewMenu(false)}
                                    >
                                        Kitchen Exhaust Hood Cleaning
                                    </Link>
                        
                                    <Link
                                        href={route('service-reports.create', {
                                            template: 'fs',
                                            ...(prefill_account?.id ? { account_id: prefill_account.id } : {}),
                                        })}
                                        className="dropdown-item"
                                        onClick={() => setShowNewMenu(false)}
                                    >
                                        Fire Suppression
                                    </Link>
                        
                                    <Link
                                        href={route('service-reports.create', {
                                            template: 'gi',
                                            ...(prefill_account?.id ? { account_id: prefill_account.id } : {}),
                                        })}
                                        className="dropdown-item"
                                        onClick={() => setShowNewMenu(false)}
                                    >
                                        Grease Interceptor
                                    </Link>
                        
                                    <Link
                                        href={route('service-reports.create', {
                                            template: 'fa',
                                            ...(prefill_account?.id ? { account_id: prefill_account.id } : {}),
                                        })}
                                        className="dropdown-item"
                                        onClick={() => setShowNewMenu(false)}
                                    >
                                        Fire Alarm System
                                    </Link>
                        
                                    <Link
                                        href={route('service-reports.create', {
                                            template: 'pe',
                                            ...(prefill_account?.id ? { account_id: prefill_account.id } : {}),
                                        })}
                                        className="dropdown-item"
                                        onClick={() => setShowNewMenu(false)}
                                    >
                                        Portable Extinguishers & Emergency Lights
                                    </Link>
                                </div>
                            )}
                        </div>                            
                    
                            <Link
                                href={route('service-reports.index')}
                                className="btn btn-outline-success"
                            >
                                Back
                            </Link>
                        </div>
                    </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">
                                {accountDisplayName || 'New Service Report'}
                            </div>
                            <div className="text-white-50 small">
                                {accountDisplayName ? `New ${currentTemplateLabel}` : title}
                            </div>
                        </div>
                    </div>

                    <div className="text-end">
                        <div className="text-white-50 small">Report No:</div>
                        <div className="text-white fw-semibold">{form.report_number}</div>
                    </div>
                </div>

                <Card className="gd-form-card gd-subcard border-0 rounded-top-0 shadow-sm">
                    <Card.Body>
                    {!prefill_account && (
                        <Row className="g-3 mb-4">
                            <Col md={6}>
                                <Form.Group className="position-relative">
                                    <Form.Label>Account</Form.Label>
                                    <Form.Control
                                        type="text"
                                        placeholder="Type at least 2 characters to search"
                                        value={selectedAccount ? selectedAccount.label : accountQuery}
                                        onChange={(e) => {
                                            setSelectedAccount(null);
                                            setContactResults([]);
                                            setRootField('account_id', '');
                                            setAccountQuery(e.target.value);
                                        }}
                                        onFocus={() => {
                                            if (accountResults.length > 0) {
                                                setShowAccountResults(true);
                                            }
                                        }}
                                    />
                    
                                    {showAccountResults && !selectedAccount && accountResults.length > 0 && (
                                        <div
                                            className="position-absolute bg-white border rounded shadow-sm w-100 mt-1"
                                            style={{ zIndex: 20, maxHeight: '260px', overflowY: 'auto' }}
                                        >
                                            {accountResults.map((account) => (
                                                <button
                                                    key={account.id}
                                                    type="button"
                                                    className="dropdown-item py-2 sr-account-result"
                                                    style={{
                                                        background: '#fff',
                                                        color: 'inherit',
                                                        paddingLeft: '12px',
                                                        paddingRight: '12px',
                                                    }}
                                                    onMouseEnter={(e) => {
                                                        e.currentTarget.style.backgroundColor = '#e9f3ee';
                                                        e.currentTarget.style.color = '#013254';
                                                    }}
                                                    onMouseLeave={(e) => {
                                                        e.currentTarget.style.backgroundColor = '#fff';
                                                        e.currentTarget.style.color = 'inherit';
                                                    }}
                                                    onMouseDown={() => {
                                                        setSelectedAccount(account);
                                                        setContactResults([]);
                                                        setRootField('account_id', account.id);
                                                        setAccountQuery(account.label);
                                                        setAccountResults([]);
                                                        setShowAccountResults(false);
                                                    }}
                                                >
                                                    {account.label}
                                                </button>
                                            ))}
                                        </div>
                                    )}
                                </Form.Group>
                            </Col>
                        </Row>
                    )}

                        <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">
                                <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 className="d-flex gap-2">
                                    <Button type="submit" disabled={saving}>
                                        {saving ? 'Saving...' : 'Create Report'}
                                    </Button>
                                    <Link href={route('service-reports.index')} className="btn btn-outline-secondary">
                                        Cancel
                                    </Link>
                                </div>
                            </div>
                        </Form>
                    </Card.Body>
                </Card>
            </div>
        </MainLayout>
    );
}