import { Head, Link, useForm } from '@inertiajs/react';
import {
    Download,
    FileText,
    FolderOpen,
    Pencil,
    Receipt,
    Scale,
} from 'lucide-react';
import { EmptyState } from '@/components/empty-state';
import { PageHeader } from '@/components/page-header';
import { StatusBadge } from '@/components/status-badge';
import type { StatusTone } from '@/components/status-badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { usePermissions } from '@/hooks/use-permissions';
import { edit, exportMethod, index } from '@/routes/clients';
import { update as updateKyc } from '@/routes/clients/kyc';

type Matter = {
    id: string;
    matter_number: string;
    title: string;
    status: string;
    status_label: string;
    status_tone: StatusTone;
    stage: string | null;
};

type Client = {
    id: string;
    client_number: string;
    name: string;
    kind_label: string;
    status: string;
    status_label: string;
    relationship_partner: string | null;
    kyc_completed: boolean;
    created_at: string | null;
    kyc_checklist: Record<string, boolean>;
    representatives: {
        id: string;
        name: string;
        designation: string | null;
        is_primary: boolean;
    }[];
    contact_detail: {
        email: string | null;
        phone: string | null;
        address: string | null;
        category: string | null;
        rc_number: string | null;
    };
};

type Props = {
    client: Client;
    matters: Matter[];
    kycDocuments: { name: string; uploaded_at: string }[];
    kycItems: string[];
};

const KYC_LABELS: Record<string, string> = {
    id: 'Identity document',
    cac_docs: 'CAC documents',
    proof_of_address: 'Proof of address',
    mandate_letter: 'Mandate letter',
};

function Field({ label, value }: { label: string; value: string | null }) {
    return (
        <div>
            <p className="text-xs tracking-wide text-muted-foreground uppercase">
                {label}
            </p>
            <p className="mt-0.5 text-sm text-foreground">{value || '—'}</p>
        </div>
    );
}

export default function ClientShow({
    client,
    matters,
    kycDocuments,
    kycItems,
}: Props) {
    const { can } = usePermissions();

    const kyc = useForm<{
        kyc_checklist: Record<string, boolean>;
        document: File | null;
    }>({
        kyc_checklist: { ...client.kyc_checklist },
        document: null,
    });

    const saveKyc = (e: React.FormEvent) => {
        e.preventDefault();
        kyc.post(updateKyc(client.id).url, {
            preserveScroll: true,
            forceFormData: true,
        });
    };

    return (
        <>
            <Head title={client.name} />
            <div className="flex flex-col gap-6 p-4">
                <PageHeader
                    title={client.name}
                    subtitle={`${client.client_number} · ${client.kind_label}`}
                    action={
                        <div className="flex flex-wrap gap-2">
                            <Button asChild variant="outline">
                                <Link href={index()}>Back</Link>
                            </Button>
                            {can('clients.export') && (
                                <Button asChild variant="outline">
                                    <a href={exportMethod(client.id).url}>
                                        <Download /> NDPR export
                                    </a>
                                </Button>
                            )}
                            {can('contacts.edit') && (
                                <Button asChild>
                                    <Link href={edit(client.id)}>
                                        <Pencil /> Edit
                                    </Link>
                                </Button>
                            )}
                        </div>
                    }
                />

                <div className="flex flex-wrap gap-2">
                    <StatusBadge
                        tone={
                            client.status === 'active' ? 'success' : 'neutral'
                        }
                    >
                        {client.status_label}
                    </StatusBadge>
                    <StatusBadge
                        tone={client.kyc_completed ? 'success' : 'warning'}
                    >
                        KYC {client.kyc_completed ? 'complete' : 'pending'}
                    </StatusBadge>
                </div>

                <Tabs defaultValue="overview">
                    <TabsList>
                        <TabsTrigger value="overview">Overview</TabsTrigger>
                        <TabsTrigger value="matters">Matters</TabsTrigger>
                        <TabsTrigger value="invoices">Invoices</TabsTrigger>
                        <TabsTrigger value="documents">Documents</TabsTrigger>
                        <TabsTrigger value="kyc">KYC</TabsTrigger>
                    </TabsList>

                    <TabsContent value="overview">
                        <div className="grid gap-6 lg:grid-cols-2">
                            <Card>
                                <CardHeader>
                                    <CardTitle>Client record</CardTitle>
                                </CardHeader>
                                <CardContent className="grid gap-4 sm:grid-cols-2">
                                    <Field
                                        label="Client number"
                                        value={client.client_number}
                                    />
                                    <Field
                                        label="Relationship partner"
                                        value={client.relationship_partner}
                                    />
                                    <Field
                                        label="Onboarded"
                                        value={client.created_at}
                                    />
                                    <Field
                                        label="Category"
                                        value={client.contact_detail.category}
                                    />
                                </CardContent>
                            </Card>
                            <Card>
                                <CardHeader>
                                    <CardTitle>Contact</CardTitle>
                                </CardHeader>
                                <CardContent className="grid gap-4 sm:grid-cols-2">
                                    <Field
                                        label="Email"
                                        value={client.contact_detail.email}
                                    />
                                    <Field
                                        label="Phone"
                                        value={client.contact_detail.phone}
                                    />
                                    <Field
                                        label="Address"
                                        value={client.contact_detail.address}
                                    />
                                    <Field
                                        label="RC number"
                                        value={client.contact_detail.rc_number}
                                    />
                                </CardContent>
                            </Card>
                            {client.representatives.length > 0 && (
                                <Card className="lg:col-span-2">
                                    <CardHeader>
                                        <CardTitle>Representatives</CardTitle>
                                    </CardHeader>
                                    <CardContent className="p-0">
                                        <Table>
                                            <TableHeader>
                                                <TableRow>
                                                    <TableHead>Name</TableHead>
                                                    <TableHead>
                                                        Designation
                                                    </TableHead>
                                                    <TableHead>
                                                        Primary
                                                    </TableHead>
                                                </TableRow>
                                            </TableHeader>
                                            <TableBody>
                                                {client.representatives.map(
                                                    (rep) => (
                                                        <TableRow key={rep.id}>
                                                            <TableCell className="font-medium text-foreground">
                                                                {rep.name}
                                                            </TableCell>
                                                            <TableCell>
                                                                {rep.designation ??
                                                                    '—'}
                                                            </TableCell>
                                                            <TableCell>
                                                                {rep.is_primary ? (
                                                                    <StatusBadge tone="info">
                                                                        Primary
                                                                    </StatusBadge>
                                                                ) : (
                                                                    '—'
                                                                )}
                                                            </TableCell>
                                                        </TableRow>
                                                    ),
                                                )}
                                            </TableBody>
                                        </Table>
                                    </CardContent>
                                </Card>
                            )}
                        </div>
                    </TabsContent>

                    <TabsContent value="matters">
                        <Card>
                            <CardContent className="p-0">
                                {matters.length === 0 ? (
                                    <EmptyState
                                        icon={Scale}
                                        title="No matters yet"
                                        description="Matters opened for this client will appear here."
                                    />
                                ) : (
                                    <Table>
                                        <TableHeader>
                                            <TableRow>
                                                <TableHead>
                                                    Matter no.
                                                </TableHead>
                                                <TableHead>Title</TableHead>
                                                <TableHead>Stage</TableHead>
                                                <TableHead>Status</TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {matters.map((m) => (
                                                <TableRow key={m.id}>
                                                    <TableCell className="font-mono text-xs text-muted-foreground">
                                                        {m.matter_number}
                                                    </TableCell>
                                                    <TableCell className="font-medium text-foreground">
                                                        {m.title}
                                                    </TableCell>
                                                    <TableCell>
                                                        {m.stage ?? '—'}
                                                    </TableCell>
                                                    <TableCell>
                                                        <StatusBadge
                                                            tone={m.status_tone}
                                                        >
                                                            {m.status_label}
                                                        </StatusBadge>
                                                    </TableCell>
                                                </TableRow>
                                            ))}
                                        </TableBody>
                                    </Table>
                                )}
                            </CardContent>
                        </Card>
                    </TabsContent>

                    <TabsContent value="invoices">
                        <Card>
                            <CardContent className="p-0">
                                <EmptyState
                                    icon={Receipt}
                                    title="Invoices arrive with billing"
                                    description="Client invoices will appear here once the Time & Billing module (M06) is live."
                                />
                            </CardContent>
                        </Card>
                    </TabsContent>

                    <TabsContent value="documents">
                        <Card>
                            <CardContent className="p-0">
                                <EmptyState
                                    icon={FolderOpen}
                                    title="Documents arrive with the DMS"
                                    description="Client documents will appear here once the Documents module (M08) is live."
                                />
                            </CardContent>
                        </Card>
                    </TabsContent>

                    <TabsContent value="kyc">
                        <div className="grid gap-6 lg:grid-cols-2">
                            <Card>
                                <CardHeader>
                                    <CardTitle>KYC checklist</CardTitle>
                                </CardHeader>
                                <form onSubmit={saveKyc}>
                                    <CardContent className="space-y-4">
                                        <div className="space-y-3">
                                            {kycItems.map((item) => (
                                                <label
                                                    key={item}
                                                    className="flex items-center gap-3"
                                                >
                                                    <Checkbox
                                                        checked={
                                                            kyc.data
                                                                .kyc_checklist[
                                                                item
                                                            ] ?? false
                                                        }
                                                        onCheckedChange={(v) =>
                                                            kyc.setData(
                                                                'kyc_checklist',
                                                                {
                                                                    ...kyc.data
                                                                        .kyc_checklist,
                                                                    [item]:
                                                                        v ===
                                                                        true,
                                                                },
                                                            )
                                                        }
                                                        disabled={
                                                            !can(
                                                                'contacts.edit',
                                                            )
                                                        }
                                                    />
                                                    <span className="text-sm">
                                                        {KYC_LABELS[item] ??
                                                            item}
                                                    </span>
                                                </label>
                                            ))}
                                        </div>
                                        {can('contacts.edit') && (
                                            <>
                                                <div className="grid gap-2">
                                                    <label className="text-xs tracking-wide text-muted-foreground uppercase">
                                                        Upload document
                                                        (optional)
                                                    </label>
                                                    <Input
                                                        type="file"
                                                        onChange={(e) =>
                                                            kyc.setData(
                                                                'document',
                                                                e.target
                                                                    .files?.[0] ??
                                                                    null,
                                                            )
                                                        }
                                                    />
                                                </div>
                                                <Button
                                                    type="submit"
                                                    disabled={kyc.processing}
                                                >
                                                    {kyc.processing && (
                                                        <Spinner />
                                                    )}
                                                    Save KYC
                                                </Button>
                                            </>
                                        )}
                                    </CardContent>
                                </form>
                            </Card>
                            <Card>
                                <CardHeader>
                                    <CardTitle>Uploaded documents</CardTitle>
                                </CardHeader>
                                <CardContent className="p-0">
                                    {kycDocuments.length === 0 ? (
                                        <EmptyState
                                            icon={FileText}
                                            title="No documents uploaded"
                                            description="KYC documents you upload are stored privately."
                                        />
                                    ) : (
                                        <Table>
                                            <TableHeader>
                                                <TableRow>
                                                    <TableHead>File</TableHead>
                                                    <TableHead>
                                                        Uploaded
                                                    </TableHead>
                                                </TableRow>
                                            </TableHeader>
                                            <TableBody>
                                                {kycDocuments.map((doc) => (
                                                    <TableRow key={doc.name}>
                                                        <TableCell className="font-medium text-foreground">
                                                            {doc.name}
                                                        </TableCell>
                                                        <TableCell>
                                                            {doc.uploaded_at}
                                                        </TableCell>
                                                    </TableRow>
                                                ))}
                                            </TableBody>
                                        </Table>
                                    )}
                                </CardContent>
                            </Card>
                        </div>
                    </TabsContent>
                </Tabs>
            </div>
        </>
    );
}
